Skip to content

The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.

chore: sync Codex marketplace v5.0.0-beta.81

github-actions[bot]e64afc5e3217
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.json
index e5ceb96f..6364bf2e 100644
--- a/plugins/omo/.codex-plugin/plugin.json
+++ b/plugins/omo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "omo",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "One Codex plugin namespace for Yeongyu's local Codex components.",
"author": {
"name": "Yeongyu Kim",
diff --git a/plugins/omo/components/bootstrap/dist/cli.js b/plugins/omo/components/bootstrap/dist/cli.js
index 19d78d30..1a9edaa3 100755
--- a/plugins/omo/components/bootstrap/dist/cli.js
+++ b/plugins/omo/components/bootstrap/dist/cli.js
@@ -1003,104 +1003,37 @@ async function defaultVersionProbe2(binaryPath) {
import { copyFile as copyFile2, mkdir as mkdir7, readFile as readFile14, readdir as readdir5, rm as rm11, stat as stat5 } from "node:fs/promises";
import { join as join23 } from "node:path";
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/core.js
-var _a;
-function $constructor(name, initializer, params) {
- function init(inst, def) {
- if (!inst._zod) {
- Object.defineProperty(inst, "_zod", {
- value: {
- def,
- constr: _,
- traits: new Set
- },
- enumerable: false
- });
- }
- if (inst._zod.traits.has(name)) {
- return;
- }
- inst._zod.traits.add(name);
- initializer(inst, def);
- const proto = _.prototype;
- const keys = Object.keys(proto);
- for (let i = 0;i < keys.length; i++) {
- const k = keys[i];
- if (!(k in inst)) {
- inst[k] = proto[k].bind(inst);
- }
- }
- }
- const Parent = params?.Parent ?? Object;
-
- class Definition extends Parent {
- }
- Object.defineProperty(Definition, "name", { value: name });
- function _(def) {
- var _a;
- const inst = params?.Parent ? new Definition : this;
- init(inst, def);
- (_a = inst._zod).deferred ?? (_a.deferred = []);
- for (const fn of inst._zod.deferred) {
- fn();
- }
- return inst;
- }
- Object.defineProperty(_, "init", { value: init });
- Object.defineProperty(_, Symbol.hasInstance, {
- value: (inst) => {
- if (params?.Parent && inst instanceof params.Parent)
- return true;
- return inst?._zod?.traits?.has(name);
- }
- });
- Object.defineProperty(_, "name", { value: name });
- return _;
-}
-var $brand = Symbol("zod_brand");
-
-class $ZodAsyncError extends Error {
- constructor() {
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
- }
-}
-
-class $ZodEncodeError extends Error {
- constructor(name) {
- super(`Encountered unidirectional transform during encode: ${name}`);
- this.name = "ZodEncodeError";
- }
-}
-(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
-var globalConfig = globalThis.__zod_globalConfig;
-function config(newConfig) {
- if (newConfig)
- Object.assign(globalConfig, newConfig);
- return globalConfig;
-}
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/util.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
return values;
}
+function joinValues(array, separator = "|") {
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
+}
function jsonStringifyReplacer(_, value) {
if (typeof value === "bigint")
return value.toString();
return value;
}
-function cached(getter) {
- const set = false;
- return {
- get value() {
- if (!set) {
- const value = getter();
- Object.defineProperty(this, "value", { value });
- return value;
- }
- throw new Error("cached value already set");
+
+class Cached {
+ constructor(getter) {
+ this._getter = getter;
+ this._value = undefined;
+ }
+ get value() {
+ const getter = this._getter;
+ if (getter !== undefined) {
+ this._value = getter();
+ this._getter = undefined;
}
- };
+ return this._value;
+ }
+}
+function cached(getter) {
+ return new Cached(getter);
}
function nullish(input) {
return input === null || input === undefined;
@@ -1113,33 +1046,11 @@ function cleanRegex(source) {
function floatSafeRemainder(val, step) {
const ratio = val / step;
const roundedRatio = Math.round(ratio);
- const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance)
return 0;
return ratio - roundedRatio;
}
-var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
-function defineLazy(object, key, getter) {
- let value = undefined;
- Object.defineProperty(object, key, {
- get() {
- if (value === EVALUATING) {
- return;
- }
- if (value === undefined) {
- value = EVALUATING;
- value = getter();
- }
- return value;
- },
- set(v) {
- Object.defineProperty(object, key, {
- value: v
- });
- },
- configurable: true
- });
-}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
@@ -1148,6 +1059,56 @@ function assignProp(target, prop, value) {
configurable: true
});
}
+function rawShape(def) {
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
+ return desc?.get ? desc.get.raw : desc?.value;
+}
+function sourceShape(schema) {
+ return rawShape(schema._zod.def) ?? schema._zod.def.shape;
+}
+function deferProp(target, key, getter) {
+ Object.defineProperty(target, key, {
+ get() {
+ const value = getter();
+ assignProp(this, key, value);
+ return value;
+ },
+ enumerable: true,
+ configurable: true
+ });
+}
+function putProp(target, key, value) {
+ if (key in target)
+ assignProp(target, key, value);
+ else
+ target[key] = value;
+}
+function mirrorShape(target, source, keys, wrap) {
+ const raw = sourceShape(source);
+ for (const key of keys) {
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
+ if (!desc.enumerable)
+ continue;
+ if (desc.get) {
+ deferProp(target, key, () => {
+ const value = source._zod.def.shape[key];
+ return wrap ? wrap(value, key) : value;
+ });
+ } else
+ putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
+ }
+}
+function mirrorProps(target, source) {
+ for (const key of Reflect.ownKeys(source)) {
+ const desc = Object.getOwnPropertyDescriptor(source, key);
+ if (!desc.enumerable)
+ continue;
+ if (desc.get)
+ deferProp(target, key, () => source[key]);
+ else
+ putProp(target, key, desc.value);
+ }
+}
function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
@@ -1234,17 +1195,28 @@ function normalizeParams(_params) {
return { ...params, error: () => params.error };
return params;
}
+function stringifyPrimitive(value) {
+ if (typeof value === "bigint")
+ return value.toString() + "n";
+ if (typeof value === "string")
+ return `"${value}"`;
+ return `${value}`;
+}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
+ return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional";
});
}
-var NUMBER_FORMAT_RANGES = {
+var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
+}))();
+var BIGINT_FORMAT_RANGES = {
+ int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
+ uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
};
function pick(schema, mask) {
const currDef = schema._zod.def;
@@ -1253,23 +1225,21 @@ function pick(schema, mask) {
if (hasChecks) {
throw new Error(".pick() cannot be used on object schemas containing refinements");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const newShape = {};
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- newShape[key] = currDef.shape[key];
- }
- assignProp(this, "shape", newShape);
- return newShape;
- },
- checks: []
- });
- return clone(schema, def);
+ const newShape = {};
+ mirrorShape(newShape, schema, maskedKeys(schema, mask));
+ return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
+}
+function maskedKeys(schema, mask) {
+ const raw = sourceShape(schema);
+ const keys = [];
+ for (const key of Reflect.ownKeys(mask)) {
+ if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {
+ throw new Error(`Unrecognized key: "${String(key)}"`);
+ }
+ if (mask[key])
+ keys.push(key);
+ }
+ return keys;
}
function omit(schema, mask) {
const currDef = schema._zod.def;
@@ -1278,23 +1248,10 @@ function omit(schema, mask) {
if (hasChecks) {
throw new Error(".omit() cannot be used on object schemas containing refinements");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const newShape = { ...schema._zod.def.shape };
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- delete newShape[key];
- }
- assignProp(this, "shape", newShape);
- return newShape;
- },
- checks: []
- });
- return clone(schema, def);
+ const omitted = new Set(maskedKeys(schema, mask));
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));
+ return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
}
function extend(schema, shape) {
if (!isPlainObject(shape)) {
@@ -1303,45 +1260,39 @@ function extend(schema, shape) {
const checks = schema._zod.def.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
- const existingShape = schema._zod.def.shape;
- for (const key in shape) {
+ const existingShape = sourceShape(schema);
+ for (const key of Reflect.ownKeys(shape)) {
if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
}
}
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- }
- });
- return clone(schema, def);
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
+}
+function extended(schema, shape) {
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
+ mirrorProps(newShape, shape);
+ return newShape;
}
function safeExtend(schema, shape) {
if (!isPlainObject(shape)) {
throw new Error("Invalid input to safeExtend: expected a plain object");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- }
- });
- return clone(schema, def);
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
}
function merge(a, b) {
+ if (!b?._zod?.def) {
+ throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
+ }
if (a._zod.def.checks?.length) {
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
}
+ const newShape = {};
+ mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));
+ mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));
const def = mergeDefs(a._zod.def, {
- get shape() {
- const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
- assignProp(this, "shape", _shape);
- return _shape;
- },
+ shape: newShape,
get catchall() {
return b._zod.def.catchall;
},
@@ -1349,74 +1300,23 @@ function merge(a, b) {
});
return clone(a, def);
}
-function partial(Class, schema, mask) {
+function partial(Class, schema, mask, name = "partial") {
const currDef = schema._zod.def;
const checks = currDef.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
- throw new Error(".partial() cannot be used on object schemas containing refinements");
- }
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in oldShape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- } else {
- for (const key in oldShape) {
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- }
- assignProp(this, "shape", shape);
- return shape;
- },
- checks: []
- });
- return clone(schema, def);
+ throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
+ }
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && ((value, key) => selected && !selected.has(key) ? value : new Class({ type: "optional", innerType: value })));
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));
}
function required(Class, schema, mask) {
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- } else {
- for (const key in oldShape) {
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- }
- assignProp(this, "shape", shape);
- return shape;
- }
- });
- return clone(schema, def);
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => selected && !selected.has(key) ? value : new Class({ type: "nonoptional", innerType: value }));
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));
}
function aborted(x, startIndex = 0) {
if (x.aborted === true)
@@ -1449,15 +1349,49 @@ function prefixIssues(path, issues) {
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
+function attachSchema(issues, start, inst) {
+ var _a;
+ for (let i = start;i < issues.length; i++) {
+ (_a = issues[i]).schema ?? (_a.schema = inst);
+ }
+}
function finalizeIssue(iss, ctx, config) {
- const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
- const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
- rest.path ?? (rest.path = []);
- rest.message = message;
+ var _a;
+ const traits = iss.inst?._zod?.traits;
+ if (traits?.has("$ZodType")) {
+ if (traits.has("$ZodCheck"))
+ (_a = iss).schema ?? (_a.schema = iss.inst);
+ else
+ iss.schema = iss.inst;
+ }
+ const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
+ const full = {};
+ for (const k of Object.keys(iss)) {
+ if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__")
+ continue;
+ full[k] = iss[k];
+ }
+ full.path ?? (full.path = []);
+ full.message = message;
if (ctx?.reportInput) {
- rest.input = _input;
+ full.input = iss.input;
}
- return rest;
+ return full;
+}
+var highSurrogate = /[\uD800-\uDBFF]/;
+function codePointLength(str) {
+ const units = str.length;
+ if (!highSurrogate.test(str))
+ return units;
+ let count = units;
+ for (let i = 0;i < units - 1; i++) {
+ if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
+ count--;
+ i++;
+ }
+ }
+ return count;
}
function getLengthableOrigin(input) {
if (Array.isArray(input))
@@ -1466,6 +1400,27 @@ function getLengthableOrigin(input) {
return "string";
return "unknown";
}
+function parsedType(data) {
+ const t = typeof data;
+ switch (t) {
+ case "number": {
+ return Number.isNaN(data) ? "nan" : "number";
+ }
+ case "object": {
+ if (data === null) {
+ return "null";
+ }
+ if (Array.isArray(data)) {
+ return "array";
+ }
+ const obj = data;
+ if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
+ return obj.constructor.name;
+ }
+ }
+ }
+ return t;
+}
function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") {
@@ -1478,138 +1433,484 @@ function issue(...args) {
}
return { ...iss };
}
-
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/errors.js
-var initializer = (inst, def) => {
- inst.name = "$ZodError";
- Object.defineProperty(inst, "_zod", {
- value: inst._zod,
- enumerable: false
- });
- Object.defineProperty(inst, "issues", {
- value: def,
- enumerable: false
- });
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
- Object.defineProperty(inst, "toString", {
- value: () => inst.message,
- enumerable: false
+function members(proto, table) {
+ for (const key in table) {
+ const desc = Object.getOwnPropertyDescriptor(table, key);
+ if (desc.get)
+ Object.defineProperty(proto, key, { ...desc, enumerable: false });
+ else
+ defineBound(proto, key, desc.value);
+ }
+}
+function own(inst, key, value, enumerable = true) {
+ Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });
+ return value;
+}
+function hide(inst, key, value) {
+ return own(inst, key, value, false);
+}
+function derived(computes, table) {
+ for (const key in computes) {
+ const compute = computes[key];
+ Object.defineProperty(table, key, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ return own(this, key, compute(this));
+ },
+ set(value) {
+ own(this, key, value);
+ }
+ });
+ }
+ return table;
+}
+function defineBound(proto, key, fn) {
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ return this == null ? fn : own(this, key, fn.bind(this));
+ },
+ set(value) {
+ own(this, key, value);
+ }
});
+}
+function claim(inst, sentinel) {
+ const proto = Object.getPrototypeOf(inst);
+ return sentinel in proto ? undefined : proto;
+}
+var installing;
+var broke = false;
+var breaker = {
+ configurable: true,
+ get() {
+ broke = true;
+ return;
+ }
};
-var $ZodError = $constructor("$ZodError", initializer);
-var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
-function flattenError(error, mapper = (issue) => issue.message) {
- const fieldErrors = {};
- const formErrors = [];
- for (const sub of error.issues) {
- if (sub.path.length > 0) {
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
- fieldErrors[sub.path[0]].push(mapper(sub));
- } else {
- formErrors.push(mapper(sub));
- }
+function defineLazyInternal(inst, key, compute) {
+ const proto = Object.getPrototypeOf(inst._zod);
+ if (key in proto && installing !== inst._zod) {
+ installing = undefined;
+ return;
}
- return { formErrors, fieldErrors };
-}
-function formatError(error, mapper = (issue) => issue.message) {
- const fieldErrors = { _errors: [] };
- const processError = (error, path = []) => {
- for (const issue of error.issues) {
- if (issue.code === "invalid_union" && issue.errors.length) {
- issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
- } else if (issue.code === "invalid_key") {
- processError({ issues: issue.issues }, [...path, ...issue.path]);
- } else if (issue.code === "invalid_element") {
- processError({ issues: issue.issues }, [...path, ...issue.path]);
- } else {
- const fullpath = [...path, ...issue.path];
- if (fullpath.length === 0) {
- fieldErrors._errors.push(mapper(issue));
- } else {
- let curr = fieldErrors;
- let i = 0;
- while (i < fullpath.length) {
- const el = fullpath[i];
- const terminal = i === fullpath.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- } else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue));
- }
- curr = curr[el];
- i++;
- }
- }
+ installing = inst._zod;
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ Object.defineProperty(this, key, breaker);
+ const outer = broke;
+ broke = false;
+ try {
+ const value = compute(this);
+ if (broke)
+ delete this[key];
+ else
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
+ broke = broke || outer;
+ return value;
+ } catch (err) {
+ delete this[key];
+ broke = broke || outer;
+ throw err;
}
+ },
+ set(value) {
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
}
- };
- processError(error);
- return fieldErrors;
+ });
+}
+function installLazyProp(inst, key, make, enumerable) {
+ const proto = claim(inst, key);
+ if (!proto)
+ return;
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ const desc = { configurable: true, writable: true, enumerable, value: undefined };
+ Object.defineProperty(this, key, desc);
+ desc.value = make(this);
+ Object.defineProperty(this, key, desc);
+ return desc.value;
+ },
+ set(value) {
+ Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });
+ }
+ });
+}
+var CONSTANT_CATCH = "~constantCatch";
+function constantCatch(value) {
+ const fn = () => value;
+ fn[CONSTANT_CATCH] = true;
+ return fn;
}
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/parse.js
-var _parse = (_Err) => (schema, value, _ctx, _params) => {
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
- const result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise) {
- throw new $ZodAsyncError;
- }
- if (result.issues.length) {
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, _params?.callee);
- throw e;
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/core.js
+var _a;
+var _zodDesc = { value: undefined, enumerable: false };
+var _E = "captureStackTrace" in Error ? Error : null;
+function newError(Definition) {
+ const E = _E;
+ if (E) {
+ const saved = E.stackTraceLimit;
+ if (typeof saved === "number") {
+ try {
+ E.stackTraceLimit = 0;
+ } catch {
+ _E = null;
+ return new Definition;
+ }
+ try {
+ return new Definition;
+ } finally {
+ E.stackTraceLimit = saved;
+ }
+ }
}
- return result.value;
-};
-var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
- const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
- let result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise)
- result = await result;
- if (result.issues.length) {
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, params?.callee);
- throw e;
+ return new Definition;
+}
+function $constructor(name, initializer, proto, params) {
+ const zodProto = {};
+ function Internals(def) {
+ this.def = def;
+ this.constr = _;
+ this.traits = new Set;
}
- return result.value;
-};
+ Internals.prototype = zodProto;
+ const protoMembers = proto;
+ const initialized = protoMembers && new WeakSet;
+ function init(inst, def) {
+ if (!inst._zod) {
+ _zodDesc.value = new Internals(def);
+ try {
+ Object.defineProperty(inst, "_zod", _zodDesc);
+ } finally {
+ _zodDesc.value = undefined;
+ }
+ } else if (inst._zod.traits.has(name)) {
+ return;
+ }
+ inst._zod.traits.add(name);
+ initializer(inst, def);
+ if (initialized) {
+ const own = Object.getPrototypeOf(inst);
+ const ctorProto = inst._zod.constr.prototype;
+ let up = own;
+ while (up && up !== ctorProto)
+ up = Object.getPrototypeOf(up);
+ const target = up ?? own;
+ if (!initialized.has(target)) {
+ initialized.add(target);
+ members(target, protoMembers);
+ }
+ }
+ const proto = _.prototype;
+ for (const k in proto) {
+ if (!Object.prototype.hasOwnProperty.call(proto, k))
+ continue;
+ if (!(k in inst)) {
+ inst[k] = proto[k].bind(inst);
+ }
+ }
+ }
+ const Parent = params?.Parent ?? Object;
+
+ class Definition extends Parent {
+ }
+ Object.defineProperty(Definition, "name", { value: name });
+ function _(def) {
+ const inst = params?.Parent ? newError(Definition) : this;
+ init(inst, def);
+ const deferred = inst._zod.deferred;
+ if (deferred) {
+ for (const fn of deferred) {
+ fn();
+ }
+ inst._zod.deferred = undefined;
+ }
+ const pp = globalThis.__zod_globalConfig?.postProcessor;
+ if (pp)
+ pp(inst);
+ return inst;
+ }
+ Object.defineProperty(_, "init", { value: init });
+ Object.defineProperty(_, Symbol.hasInstance, {
+ value: (inst) => {
+ if (params?.Parent && inst instanceof params.Parent)
+ return true;
+ return inst?._zod?.traits?.has(name);
+ }
+ });
+ Object.defineProperty(_, "name", { value: name });
+ return _;
+}
+class $ZodAsyncError extends Error {
+ constructor() {
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
+ }
+}
+
+class $ZodEncodeError extends Error {
+ constructor(name) {
+ super(`Encountered unidirectional transform during encode: ${name}`);
+ this.name = "ZodEncodeError";
+ }
+}
+(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
+var globalConfig = globalThis.__zod_globalConfig;
+function config(newConfig) {
+ if (newConfig)
+ Object.assign(globalConfig, newConfig);
+ return globalConfig;
+}
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/errors.js
+function _getMessage() {
+ const internals = this._zod;
+ internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
+ return internals.message;
+}
+function _setMessage(value) {
+ this._zod.message = value;
+}
+var _messageDesc = {
+ get: _getMessage,
+ set: _setMessage,
+ enumerable: true,
+ configurable: true
+};
+var _issuesDesc = { value: undefined, enumerable: false };
+var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
+var initializer = (inst, def) => {
+ inst.name = "$ZodError";
+ _issuesDesc.value = def;
+ Object.defineProperty(inst, "issues", _issuesDesc);
+ _issuesDesc.value = undefined;
+ Object.defineProperty(inst, "message", _messageDesc);
+ const proto = Object.getPrototypeOf(inst);
+ if (!_installedToString.has(proto)) {
+ _installedToString.add(proto);
+ Object.defineProperty(proto, "toString", {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const value = () => this.message;
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
+ return value;
+ },
+ set(value) {
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
+ }
+ });
+ }
+};
+var $ZodError = $constructor("$ZodError", initializer);
+var $ZodRealError = $constructor("$ZodError", initializer, undefined, {
+ Parent: Error
+});
+function node(obj, key, make) {
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) {
+ if (key === "__proto__") {
+ Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
+ } else {
+ obj[key] = make();
+ }
+ }
+ return obj[key];
+}
+function flattenError(error, mapper = (issue) => issue.message) {
+ const fieldErrors = {};
+ const formErrors = [];
+ for (const sub of error.issues) {
+ if (sub.path.length > 0) {
+ node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
+ } else {
+ formErrors.push(mapper(sub));
+ }
+ }
+ return { formErrors, fieldErrors };
+}
+function formatError(error, mapper = (issue) => issue.message) {
+ const fieldErrors = { _errors: [] };
+ const processError = (error, path = []) => {
+ for (const issue of error.issues) {
+ if (issue.code === "invalid_union" && issue.errors.length) {
+ issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
+ } else if (issue.code === "invalid_key") {
+ processError({ issues: issue.issues }, [...path, ...issue.path]);
+ } else if (issue.code === "invalid_element") {
+ processError({ issues: issue.issues }, [...path, ...issue.path]);
+ } else {
+ const fullpath = [...path, ...issue.path];
+ if (fullpath.length === 0) {
+ fieldErrors._errors.push(mapper(issue));
+ } else {
+ let curr = fieldErrors;
+ let i = 0;
+ while (i < fullpath.length) {
+ const el = fullpath[i];
+ const terminal = i === fullpath.length - 1;
+ if (el === "_errors") {
+ if (terminal)
+ curr._errors.push(mapper(issue));
+ i++;
+ continue;
+ }
+ if (!Object.prototype.hasOwnProperty.call(curr, el)) {
+ Object.defineProperty(curr, el, {
+ value: { _errors: [] },
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ const node = curr[el];
+ if (terminal) {
+ node._errors.push(mapper(issue));
+ }
+ curr = node;
+ i++;
+ }
+ }
+ }
+ }
+ };
+ processError(error);
+ return fieldErrors;
+}
+
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/parse.js
+function finalizeParams(callee, params) {
+ return { callee: params?.callee ?? callee, Err: params?.Err };
+}
+var _parse = (_Err) => {
+ const fn = (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
+ const result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ throw new $ZodAsyncError;
+ }
+ if (result.issues.length) {
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, _params?.callee ?? fn);
+ throw e;
+ }
+ return result.value;
+ };
+ return fn;
+};
+var _parseAsync = (_Err) => {
+ const fn = async (schema, value, _ctx, params) => {
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ if (result.issues.length) {
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, params?.callee ?? fn);
+ throw e;
+ }
+ return result.value;
+ };
+ return fn;
+};
var _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new $ZodAsyncError;
}
- return result.issues.length ? {
- success: false,
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
+ return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
};
-var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
+function failure(Err, issues, ctx) {
+ let error;
+ return {
+ success: false,
+ get error() {
+ if (!error) {
+ error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ issues = undefined;
+ ctx = undefined;
+ }
+ return error;
+ },
+ set error(e) {
+ error = e;
+ issues = undefined;
+ ctx = undefined;
+ }
+ };
+}
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
- return result.issues.length ? {
- success: false,
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
+ return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
};
-var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
-var _encode = (_Err) => (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
- return _parse(_Err)(schema, value, ctx);
+var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
+var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
+var validate = (schema, value, _ctx) => {
+ const validator = schema._zod.bag.validator;
+ if (validator !== undefined) {
+ if (validator(value) !== COMPILE_INVALID)
+ return true;
+ if (validator.definite === true && _ctx === undefined)
+ return false;
+ }
+ return validateFallback(schema, value, _ctx);
};
-var _decode = (_Err) => (schema, value, _ctx) => {
- return _parse(_Err)(schema, value, _ctx);
+function validateFallback(schema, value, _ctx) {
+ const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true };
+ const fallbackRun = schema._zod.bag.fallbackRun;
+ let result;
+ if (fallbackRun) {
+ ctx[COMPILE_FALLBACK] = true;
+ result = fallbackRun({ value, issues: [] }, ctx);
+ } else {
+ result = schema._zod.run({ value, issues: [] }, ctx);
+ }
+ if (result instanceof Promise) {
+ throw new $ZodAsyncError;
+ }
+ return result.issues.length === 0;
+}
+var validateAsync = async (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ return result.issues.length === 0;
};
-var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
- return _parseAsync(_Err)(schema, value, ctx);
+var _encode = (_Err) => {
+ const parse = _parse(_Err);
+ const fn = (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return parse(schema, value, ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+};
+var _decode = (_Err) => {
+ const parse = _parse(_Err);
+ const fn = (schema, value, _ctx, _params) => {
+ return parse(schema, value, _ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+};
+var _encodeAsync = (_Err) => {
+ const parseAsync = _parseAsync(_Err);
+ const fn = async (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return await parseAsync(schema, value, ctx, finalizeParams(fn, _params));
+ };
+ return fn;
};
-var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
- return _parseAsync(_Err)(schema, value, _ctx);
+var _decodeAsync = (_Err) => {
+ const parseAsync = _parseAsync(_Err);
+ const fn = async (schema, value, _ctx, _params) => {
+ return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
+ };
+ return fn;
};
var _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
@@ -1625,13 +1926,16 @@ var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
return _safeParseAsync(_Err)(schema, value, _ctx);
};
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/regexes.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/regexes.js
var cuid = /^[cC][0-9a-z]{6,}$/;
var cuid2 = /^[0-9a-z]+$/;
-var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
+var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
var xid = /^[0-9a-vA-V]{20}$/;
var ksuid = /^[A-Za-z0-9]{27}$/;
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
+function nanoidOfLength(length) {
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
+}
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var 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})$/;
var uuid = (version) => {
@@ -1639,56 +1943,58 @@ var uuid = (version) => {
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)$/;
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})$`);
};
-var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
-var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
+var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
+var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
function emoji() {
return new RegExp(_emoji, "u");
}
var 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])$/;
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
var 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])$/;
-var 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])$/;
+var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
-var base64url = /^[A-Za-z0-9_-]*$/;
+var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
var httpProtocol = /^https?$/;
var e164 = /^\+[1-9]\d{6,14}$/;
var 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])))`;
-var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
+function anchor(source) {
+ return new RegExp(`^${source}$`);
+}
+var date = /* @__PURE__ */ anchor(dateSource);
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
- const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
+ const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
return regex;
}
function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
- const time = timeSource({ precision: args.precision });
const opts = ["Z"];
- if (args.local)
- opts.push("");
if (args.offset)
opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
- const timeRegex = `${time}(?:${opts.join("|")})`;
+ const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
-var string = (params) => {
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
- return new RegExp(`^${regex}$`);
-};
+var anyString = /^[\s\S]{0,}$/;
var integer = /^-?\d+$/;
var number = /^-?\d+(?:\.\d+)?$/;
var boolean = /^(?:true|false)$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/checks.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/checks.js
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
+var _whenHasLength = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.length !== undefined;
+};
var numericOriginMap = {
number: "number",
bigint: "bigint",
@@ -1697,22 +2003,12 @@ var numericOriginMap = {
var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
- if (def.value < curr) {
- if (def.inclusive)
- bag.maximum = def.value;
- else
- bag.exclusiveMaximum = def.value;
- }
- });
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
- origin,
+ origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
@@ -1725,22 +2021,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst,
var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
- if (def.value > curr) {
- if (def.inclusive)
- bag.minimum = def.value;
- else
- bag.exclusiveMinimum = def.value;
- }
- });
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
- origin,
+ origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
@@ -1752,14 +2038,10 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan",
});
var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
- inst._zod.onattach.push((inst) => {
- var _a;
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
- });
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
- const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
+ const isMultiple = typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
@@ -1778,14 +2060,6 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.format = def.format;
- bag.minimum = minimum;
- bag.maximum = maximum;
- if (isInt)
- bag.pattern = integer;
- });
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
@@ -1854,18 +2128,11 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
- if (def.maximum < curr)
- inst._zod.bag.maximum = def.maximum;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units;
if (length <= def.maximum)
return;
const origin = getLengthableOrigin(input);
@@ -1883,18 +2150,11 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins
var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
- if (def.minimum > curr)
- inst._zod.bag.minimum = def.minimum;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units;
if (length >= def.minimum)
return;
const origin = getLengthableOrigin(input);
@@ -1912,19 +2172,11 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins
var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.minimum = def.length;
- bag.maximum = def.length;
- bag.length = def.length;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
if (length === def.length)
return;
const origin = getLengthableOrigin(input);
@@ -1943,14 +2195,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals"
var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.format = def.format;
- if (def.pattern) {
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(def.pattern);
- }
- });
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
@@ -1997,13 +2241,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = escapeRegex(def.includes);
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
@@ -2022,11 +2261,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
@@ -2045,11 +2279,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst,
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
@@ -2071,18 +2300,21 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins
};
});
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/doc.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/doc.js
class Doc {
- constructor(args = []) {
+ constructor(args = [], closed = {}) {
this.content = [];
this.indent = 0;
- if (this)
- this.args = args;
+ this.args = args;
+ this.closed = closed;
}
indented(fn) {
this.indent += 1;
- fn(this);
- this.indent -= 1;
+ try {
+ fn(this);
+ } finally {
+ this.indent -= 1;
+ }
}
write(arg) {
if (typeof arg === "function") {
@@ -2101,32 +2333,31 @@ class Doc {
}
compile() {
const F = Function;
- const args = this?.args;
const content = this?.content ?? [``];
- const lines = [...content.map((x) => ` ${x}`)];
- return new F(...args, lines.join(`
-`));
+ const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {
+${content.join(`
+`)}
+};`);
+ return factory(...Object.values(this.closed));
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/versions.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/versions.js
var version = {
major: 4,
- minor: 4,
- patch: 3
+ minor: 6,
+ patch: 5
};
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/schemas.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/schemas.js
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
var _a;
inst ?? (inst = {});
inst._zod.def = def;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
- const checks = [...inst._zod.def.checks ?? []];
- if (inst._zod.traits.has("$ZodCheck")) {
- checks.unshift(inst);
- }
+ const defChecks = inst._zod.def.checks;
+ const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];
for (const ch of checks) {
for (const fn of ch._zod.onattach) {
fn(inst);
@@ -2139,6 +2370,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
});
} else {
const runChecks = (payload, checks, ctx) => {
+ if (payload.memo)
+ return payload;
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
@@ -2162,6 +2395,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
const nextLen = payload.issues.length;
if (nextLen === currLen)
return;
+ attachSchema(payload.issues, currLen, inst);
if (!isAborted)
isAborted = aborted(payload, currLen);
});
@@ -2169,6 +2403,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
const nextLen = payload.issues.length;
if (nextLen === currLen)
continue;
+ attachSchema(payload.issues, currLen, inst);
if (!isAborted)
isAborted = aborted(payload, currLen);
}
@@ -2215,22 +2450,37 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
return runChecks(result, checks, ctx);
};
}
- defineLazy(inst, "~standard", () => ({
+}, {
+ get "~standard"() {
+ return hide(this, "~standard", standardProps(this));
+ },
+ set "~standard"(value) {
+ own(this, "~standard", value);
+ }
+});
+var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value };
+async function validateAsync2(inst, value) {
+ const ctx = { async: true };
+ return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx);
+}
+function standardProps(inst) {
+ return {
validate: (value) => {
+ const ctx = { async: false };
try {
- const r = safeParse(inst, value);
- return r.success ? { value: r.data } : { issues: r.error?.issues };
- } catch (_) {
- return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
- }
+ const r = inst._zod.run({ value, issues: [] }, ctx);
+ if (!(r instanceof Promise))
+ return toStandardResult(r, ctx);
+ } catch (_) {}
+ return validateAsync2(inst, value);
},
vendor: "zod",
version: 1
- }));
-});
+ };
+}
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
+ inst._zod.pattern = def.pattern ?? anyString;
inst._zod.parse = (payload, _) => {
if (def.coerce)
try {
@@ -2279,61 +2529,108 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
+var URL_BAD_FORMAT = 1;
+var URL_UNPARSEABLE = 2;
+function canParseURL(input) {
+ try {
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function")
+ return URL.canParse(input);
+ new URL(input);
+ return true;
+ } catch {
+ return false;
+ }
+}
+function validateURL(trimmed, def) {
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
+ return canParseURL(trimmed) || URL_UNPARSEABLE;
+ }
+ return parseURLObject(trimmed, def);
+}
+function parseURLObject(trimmed, def) {
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
+ return URL_BAD_FORMAT;
+ }
+ try {
+ if (typeof URL !== "undefined") {
+ const URLStatic = URL;
+ if (typeof URLStatic.parse === "function")
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
+ }
+ return new URL(trimmed);
+ } catch {
+ return URL_UNPARSEABLE;
+ }
+}
+var asciiTabOrNewline = /[\t\n\r]/g;
+function stripTabAndNewline(value) {
+ return value.replace(asciiTabOrNewline, "");
+}
+function urlHostnameOk(url, hostname) {
+ hostname.lastIndex = 0;
+ return hostname.test(url.hostname);
+}
+function urlProtocolOk(url, protocol) {
+ protocol.lastIndex = 0;
+ return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
+}
var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const trimmed = payload.value.trim();
- if (!def.normalize && def.protocol?.source === httpProtocol.source) {
- if (!/^https?:\/\//i.test(trimmed)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid URL format",
- input: payload.value,
- inst,
- continue: !def.abort
- });
- return;
- }
+ const url = validateURL(trimmed, def);
+ if (url === URL_BAD_FORMAT) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid URL format",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
}
- const url = new URL(trimmed);
- if (def.hostname) {
- def.hostname.lastIndex = 0;
- if (!def.hostname.test(url.hostname)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid hostname",
- pattern: def.hostname.source,
- input: payload.value,
- inst,
- continue: !def.abort
- });
- }
+ if (url === URL_UNPARSEABLE) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
}
- if (def.protocol) {
- def.protocol.lastIndex = 0;
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid protocol",
- pattern: def.protocol.source,
- input: payload.value,
- inst,
- continue: !def.abort
- });
- }
+ if (url === true) {
+ payload.value = stripTabAndNewline(trimmed);
+ return;
}
- if (def.normalize) {
- payload.value = url.href;
- } else {
- payload.value = trimmed;
+ if (def.hostname && !urlHostnameOk(url, def.hostname)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid hostname",
+ pattern: def.hostname.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
}
- return;
- } catch (_) {
- payload.issues.push({
+ if (def.protocol && !urlProtocolOk(url, def.protocol)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid protocol",
+ pattern: def.protocol.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
+ return;
+ } catch (_) {
+ payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
@@ -2348,7 +2645,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
$ZodStringFormat.init(inst, def);
});
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
- def.pattern ?? (def.pattern = nanoid);
+ if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))
+ throw new Error(`Invalid nanoid length: ${def.length}`);
+ def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length));
$ZodStringFormat.init(inst, def);
});
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
@@ -2390,16 +2689,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.format = `ipv4`;
});
+var ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
+function isValidIPv6(value) {
+ if (!ipv6Alphabet.test(value))
+ return false;
+ return canParseURL(`http://[${value}]`);
+}
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.format = `ipv6`;
inst._zod.check = (payload) => {
- try {
- new URL(`http://[${payload.value}]`);
- } catch {
+ if (!isValidIPv6(payload.value)) {
payload.issues.push({
code: "invalid_format",
format: "ipv6",
@@ -2414,24 +2715,25 @@ var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
def.pattern ?? (def.pattern = cidrv4);
$ZodStringFormat.init(inst, def);
});
+function isValidCIDRv6(value) {
+ const parts = value.split("/");
+ if (parts.length !== 2)
+ return false;
+ const [address, prefix] = parts;
+ if (!prefix)
+ return false;
+ const prefixNum = Number(prefix);
+ if (`${prefixNum}` !== prefix)
+ return false;
+ if (prefixNum < 0 || prefixNum > 128)
+ return false;
+ return isValidIPv6(address);
+}
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
- const parts = payload.value.split("/");
- try {
- if (parts.length !== 2)
- throw new Error;
- const [address, prefix] = parts;
- if (!prefix)
- throw new Error;
- const prefixNum = Number(prefix);
- if (`${prefixNum}` !== prefix)
- throw new Error;
- if (prefixNum < 0 || prefixNum > 128)
- throw new Error;
- new URL(`http://[${address}]`);
- } catch {
+ if (!isValidCIDRv6(payload.value)) {
payload.issues.push({
code: "invalid_format",
format: "cidrv6",
@@ -2456,10 +2758,10 @@ function isValidBase64(data) {
return false;
}
}
+var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
- def.pattern ?? (def.pattern = base64);
+ def.pattern ?? (def.pattern = base64Charset);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.contentEncoding = "base64";
inst._zod.check = (payload) => {
if (isValidBase64(payload.value))
return;
@@ -2472,17 +2774,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
});
};
});
+var base64urlCharset = /^[A-Za-z0-9_-]*$/;
function isValidBase64URL(data) {
- if (!base64url.test(data))
+ if (!base64urlCharset.test(data))
return false;
const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
return isValidBase64(padded);
}
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
- def.pattern ?? (def.pattern = base64url);
+ def.pattern ?? (def.pattern = base64urlCharset);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.contentEncoding = "base64url";
inst._zod.check = (payload) => {
if (isValidBase64URL(payload.value))
return;
@@ -2535,7 +2837,7 @@ var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
});
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.pattern = inst._zod.bag.pattern ?? number;
+ inst._zod.pattern = number;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce)
try {
@@ -2545,7 +2847,7 @@ var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
return payload;
}
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined;
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : undefined : undefined;
payload.issues.push({
expected: "number",
code: "invalid_type",
@@ -2604,6 +2906,8 @@ function handleArrayResult(result, final, index) {
}
var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
$ZodType.init(inst, def);
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!Array.isArray(input)) {
@@ -2615,8 +2919,9 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
});
return payload;
}
- payload.value = Array(input.length);
+ payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);
const proms = [];
+ const abortEarly = ctx?.abortEarly;
for (let i = 0;i < input.length; i++) {
const item = input[i];
const result = def.element._zod.run({
@@ -2627,6 +2932,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
proms.push(result.then((result) => handleArrayResult(result, payload, i)));
} else {
handleArrayResult(result, payload, i);
+ if (abortEarly && result.issues.length !== 0 && aborted(result))
+ break;
}
}
if (proms.length) {
@@ -2635,15 +2942,19 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
return payload;
};
});
-function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
+function handlePropertyResult(result, final, key, input, optin, optout) {
const isPresent = key in input;
+ const isOptionalOut = optout === "optional";
+ if (!isPresent && isOptionalOut && optin === "optional") {
+ return;
+ }
if (result.issues.length) {
- if (isOptionalIn && isOptionalOut && !isPresent) {
+ if (optin !== undefined && isOptionalOut && !isPresent) {
return;
}
final.issues.push(...prefixIssues(key, result.issues));
}
- if (!isPresent && !isOptionalIn) {
+ if (!isPresent && optin === undefined) {
if (!result.issues.length) {
final.issues.push({
code: "invalid_type",
@@ -2655,50 +2966,64 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona
return;
}
if (result.value === undefined) {
- if (isPresent) {
+ if (isPresent || optin === "defaulted" && !isOptionalOut) {
final.value[key] = undefined;
}
} else {
final.value[key] = result.value;
}
}
+var NO_SYMBOL_KEYS = [];
function normalizeDef(def) {
const keys = Object.keys(def.shape);
- for (const k of keys) {
+ const ownSymbols = Object.getOwnPropertySymbols(def.shape);
+ const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
+ const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
+ for (const k of allKeys) {
if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
+ throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
}
}
const okeys = optionalKeys(def.shape);
return {
...def,
- keys,
+ allKeys,
+ symbolKeys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
}
-function handleCatchall(proms, input, payload, ctx, def, inst) {
+function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {
const unrecognized = [];
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
- const isOptionalIn = _catchall.optin === "optional";
- const isOptionalOut = _catchall.optout === "optional";
+ const optin = _catchall.optin;
+ const optout = _catchall.optout;
+ let seen = 0;
for (const key in input) {
- if (key === "__proto__")
- continue;
+ if (abortEarly && payload.issues.length !== seen) {
+ if (aborted(payload, seen))
+ break;
+ seen = payload.issues.length;
+ }
if (keySet.has(key))
continue;
+ if (key === "__proto__") {
+ if (t === "never")
+ unrecognized.push(key);
+ continue;
+ }
if (t === "never") {
unrecognized.push(key);
continue;
}
const r = _catchall.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
} else {
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ handlePropertyResult(r, payload, key, input, optin, optout);
}
}
if (unrecognized.length) {
@@ -2706,7 +3031,8 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
code: "unrecognized_keys",
keys: unrecognized,
input,
- inst
+ inst,
+ continue: true
});
}
if (!proms.length)
@@ -2718,28 +3044,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
const desc = Object.getOwnPropertyDescriptor(def, "shape");
- if (!desc?.get) {
- const sh = def.shape;
- Object.defineProperty(def, "shape", {
- get: () => {
- const newSh = { ...sh };
- Object.defineProperty(def, "shape", {
- value: newSh
- });
- return newSh;
- }
- });
+ const sh = desc?.get ? desc.get.raw : def.shape ?? {};
+ if (sh) {
+ const get = () => {
+ const newSh = { ...sh };
+ Object.defineProperty(def, "shape", { value: newSh });
+ get.raw = newSh;
+ return newSh;
+ };
+ get.raw = sh;
+ Object.defineProperty(def, "shape", { get });
}
const _normalized = cached(() => normalizeDef(def));
- defineLazy(inst._zod, "propValues", () => {
- const shape = def.shape;
+ defineLazyInternal(inst, "propValues", (zod) => {
+ const shape = zod.def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
- propValues[key] ?? (propValues[key] = new Set);
+ if (!Object.prototype.hasOwnProperty.call(propValues, key)) {
+ assignProp(propValues, key, new Set);
+ }
for (const v of field.values)
propValues[key].add(v);
+ if (field.optin !== undefined)
+ propValues[key].add(undefined);
}
}
return propValues;
@@ -2747,6 +3076,8 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
const isObject2 = isObject;
const catchall = def.catchall;
let value;
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
@@ -2759,79 +3090,93 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
});
return payload;
}
- payload.value = {};
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const proms = [];
const shape = value.shape;
- for (const key of value.keys) {
+ const abortEarly = ctx?.abortEarly;
+ let seen = payload.issues.length;
+ for (const key of value.allKeys) {
+ if (abortEarly && payload.issues.length !== seen) {
+ if (aborted(payload, seen))
+ break;
+ seen = payload.issues.length;
+ }
+ if (key === "__proto__")
+ continue;
const el = shape[key];
- const isOptionalIn = el._zod.optin === "optional";
- const isOptionalOut = el._zod.optout === "optional";
+ const optin = el._zod.optin;
+ const optout = el._zod.optout;
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
} else {
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ handlePropertyResult(r, payload, key, input, optin, optout);
}
}
if (!catchall) {
return proms.length ? Promise.all(proms).then(() => payload) : payload;
}
- return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
};
});
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
$ZodObject.init(inst, def);
const superParse = inst._zod.parse;
const _normalized = cached(() => normalizeDef(def));
+ const memo = globalConfig.memoizer;
const generateFastpass = (shape) => {
- const doc = new Doc(["shape", "payload", "ctx"]);
const normalized = _normalized.value;
- const parseStr = (key) => {
- const k = esc(key);
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
- };
+ const syms = normalized.symbolKeys;
+ const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms });
+ const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
+ const prefixStr = (id, k) => `
+ let ${id}_ab = false;
+ for (let i = 0; i < ${id}.issues.length; i++) {
+ const iss = ${id}.issues[i];
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
+ payload.issues.push(iss);
+ if (iss.continue !== true) ${id}_ab = true;
+ }
+ if (${id}_ab && ctx && ctx.abortEarly) {
+ payload.value = newResult;
+ return payload;
+ }`;
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
- for (const key of normalized.keys) {
+ for (const key of normalized.allKeys) {
ids[key] = `key_${counter++}`;
}
- doc.write(`const newResult = {};`);
- for (const key of normalized.keys) {
+ doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);
+ for (const key of normalized.allKeys) {
+ if (key === "__proto__")
+ continue;
const id = ids[key];
- const k = esc(key);
+ const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
+ const isPresent = `${k} in input`;
const schema = shape[key];
- const isOptionalIn = schema?._zod?.optin === "optional";
+ const optin = schema?._zod?.optin;
+ const isOptionalIn = optin !== undefined;
const isOptionalOut = schema?._zod?.optout === "optional";
- doc.write(`const ${id} = ${parseStr(key)};`);
+ doc.write(`const ${id} = ${parseStr(k)};`);
if (isOptionalIn && isOptionalOut) {
+ const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
doc.write(`
- if (${id}.issues.length) {
- if (${k} in input) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ const ${id}_present = ${isPresent};
+ if (!${id}.issues.length || ${id}_present) {
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
- }
-
- if (${id}.value === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
+
+ if (${assign}) {
+ newResult[${k}] = ${id}.value;
}
- } else {
- newResult[${k}] = ${id}.value;
}
-
+
`);
} else if (!isOptionalIn) {
doc.write(`
- const ${id}_present = ${k} in input;
- if (${id}.issues.length) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ const ${id}_present = ${isPresent};
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
if (!${id}_present && !${id}.issues.length) {
payload.issues.push({
@@ -2840,41 +3185,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
input: undefined,
path: [${k}]
});
+ if (ctx && ctx.abortEarly) {
+ payload.value = newResult;
+ return payload;
+ }
}
if (${id}_present) {
- if (${id}.value === undefined) {
- newResult[${k}] = undefined;
- } else {
- newResult[${k}] = ${id}.value;
- }
+ newResult[${k}] = ${id}.value;
}
`);
} else {
doc.write(`
- if (${id}.issues.length) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
-
- if (${id}.value === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
- }
+ `);
+ if (optin === "defaulted") {
+ doc.write(`newResult[${k}] = ${id}.value;`);
} else {
+ doc.write(`
+ if (${id}.value !== undefined || ${isPresent}) {
newResult[${k}] = ${id}.value;
}
-
`);
+ }
}
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
- const fn = doc.compile();
- return (payload, ctx) => fn(shape, payload, ctx);
+ return doc.compile();
};
let fastpass;
const isObject2 = isObject;
@@ -2901,7 +3241,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
payload = fastpass(payload, ctx);
if (!catchall)
return payload;
- return handleCatchall([], input, payload, ctx, value, inst);
+ return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);
}
return superParse(payload, ctx);
};
@@ -2928,17 +3268,17 @@ function handleUnionResults(results, final, inst, ctx) {
}
var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "values", () => {
- if (def.options.every((o) => o._zod.values)) {
- return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
+ defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== undefined) ? "optional" : undefined);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
+ defineLazyInternal(inst, "values", (zod) => {
+ if (zod.def.options.every((o) => o._zod.values)) {
+ return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));
}
return;
});
- defineLazy(inst._zod, "pattern", () => {
- if (def.options.every((o) => o._zod.pattern)) {
- const patterns = def.options.map((o) => o._zod.pattern);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ if (zod.def.options.every((o) => o._zod.pattern)) {
+ const patterns = zod.def.options.map((o) => o._zod.pattern);
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
}
return;
@@ -2971,42 +3311,57 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
});
};
});
+function discriminatorMap(def) {
+ const map = new Map;
+ for (const option of def.options) {
+ const values = option._zod.propValues?.[def.discriminator];
+ if (!values || values.size === 0)
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ for (const value of values) {
+ if (map.has(value)) {
+ if (value !== undefined)
+ throw new Error(`Duplicate discriminator value "${String(value)}"`);
+ map.set(value, null);
+ } else {
+ map.set(value, option);
+ }
+ }
+ }
+ return map;
+}
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
def.inclusive = false;
$ZodUnion.init(inst, def);
const _super = inst._zod.parse;
- defineLazy(inst._zod, "propValues", () => {
+ defineLazyInternal(inst, "propValues", (zod) => {
const propValues = {};
- for (const option of def.options) {
+ let undefinedCount = 0;
+ for (const option of zod.def.options) {
const pv = option._zod.propValues;
if (!pv || Object.keys(pv).length === 0)
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
+ if (pv[zod.def.discriminator]?.has(undefined))
+ undefinedCount++;
for (const [k, v] of Object.entries(pv)) {
- if (!propValues[k])
- propValues[k] = new Set;
+ if (!Object.prototype.hasOwnProperty.call(propValues, k)) {
+ assignProp(propValues, k, new Set);
+ }
for (const val of v) {
propValues[k].add(val);
}
}
}
+ if (!zod.def.unionFallback && undefinedCount > 1)
+ propValues[zod.def.discriminator]?.delete(undefined);
return propValues;
});
- const disc = cached(() => {
- const opts = def.options;
- const map = new Map;
- for (const o of opts) {
- const values = o._zod.propValues?.[def.discriminator];
- if (!values || values.size === 0)
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
- for (const v of values) {
- if (map.has(v)) {
- throw new Error(`Duplicate discriminator value "${String(v)}"`);
- }
- map.set(v, o);
- }
+ def.options.forEach((option, i) => {
+ const propShape = rawShape(option._zod.def);
+ if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {
+ throw new Error(`Invalid discriminated union option at index "${i}"`);
}
- return map;
});
+ const disc = cached(() => discriminatorMap(def));
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isObject(input)) {
@@ -3018,8 +3373,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
});
return payload;
}
- const opt = disc.value.get(input?.[def.discriminator]);
- if (opt) {
+ const value = input?.[def.discriminator];
+ const opt = disc.value.get(value);
+ if (opt && (value !== undefined || ctx.direction !== "backward")) {
return opt._zod.run(payload, ctx);
}
if (def.unionFallback || ctx.direction === "backward") {
@@ -3030,7 +3386,7 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
errors: [],
note: "No matching discriminator",
discriminator: def.discriminator,
- options: Array.from(disc.value.keys()),
+ options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),
input,
path: [def.discriminator],
inst
@@ -3064,7 +3420,11 @@ function mergeValues(a, b) {
const bKeys = Object.keys(b);
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
+ if (Object.prototype.hasOwnProperty.call(newObj, "__proto__"))
+ delete newObj.__proto__;
for (const key of sharedKeys) {
+ if (key === "__proto__")
+ continue;
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return {
@@ -3100,37 +3460,49 @@ function mergeValues(a, b) {
function handleIntersectionResults(result, left, right) {
const unrecKeys = new Map;
let unrecIssue;
- for (const iss of left.issues) {
- if (iss.code === "unrecognized_keys") {
+ const keyIssues = new Map;
+ const collect = (iss, side) => {
+ let keys;
+ if (iss.code === "unrecognized_keys" && !iss.path?.length) {
unrecIssue ?? (unrecIssue = iss);
- for (const k of iss.keys) {
- if (!unrecKeys.has(k))
- unrecKeys.set(k, {});
- unrecKeys.get(k).l = true;
- }
+ keys = iss.keys;
+ } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
+ const k = String(iss.path[0]);
+ if (!keyIssues.has(k))
+ keyIssues.set(k, iss);
+ keys = [k];
} else {
- result.issues.push(iss);
+ return false;
}
+ for (const k of keys) {
+ if (!unrecKeys.has(k))
+ unrecKeys.set(k, {});
+ unrecKeys.get(k)[side] = true;
+ }
+ return true;
+ };
+ for (const iss of left.issues) {
+ if (!collect(iss, "l"))
+ result.issues.push(iss);
}
for (const iss of right.issues) {
- if (iss.code === "unrecognized_keys") {
- for (const k of iss.keys) {
- if (!unrecKeys.has(k))
- unrecKeys.set(k, {});
- unrecKeys.get(k).r = true;
- }
- } else {
+ if (!collect(iss, "r"))
result.issues.push(iss);
- }
}
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
- if (bothKeys.length && unrecIssue) {
- result.issues.push({ ...unrecIssue, keys: bothKeys });
+ if (bothKeys.length) {
+ const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
+ if (aggregated.length)
+ result.issues.push({ ...unrecIssue, keys: aggregated });
+ for (const k of bothKeys) {
+ if (!aggregated.includes(k) && keyIssues.has(k))
+ result.issues.push(keyIssues.get(k));
+ }
}
- if (aborted(result))
- return result;
const merged = mergeValues(left.value, right.value);
if (!merged.valid) {
+ if (aborted(result))
+ return result;
throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
}
result.value = merged.data;
@@ -3138,6 +3510,8 @@ function handleIntersectionResults(result, left, right) {
}
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
$ZodType.init(inst, def);
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isPlainObject(input)) {
@@ -3151,12 +3525,14 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
}
const proms = [];
const values = def.keyType._zod.values;
- if (values) {
- payload.value = {};
+ if (values && !def.partial) {
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const recordKeys = new Set;
for (const key of values) {
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
recordKeys.add(typeof key === "number" ? key.toString() : key);
+ if (key === "__proto__")
+ continue;
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
@@ -3173,6 +3549,8 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
continue;
}
const outKey = keyResult.value;
+ if (outKey === "__proto__")
+ continue;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
@@ -3192,8 +3570,14 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
let unrecognized;
for (const key in input) {
if (!recordKeys.has(key)) {
- unrecognized = unrecognized ?? [];
- unrecognized.push(key);
+ if (def.mode === "loose") {
+ if (key === "__proto__")
+ continue;
+ payload.value[key] = input[key];
+ } else {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
+ }
}
}
if (unrecognized && unrecognized.length > 0) {
@@ -3201,11 +3585,13 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
code: "unrecognized_keys",
input,
inst,
- keys: unrecognized
+ keys: unrecognized,
+ continue: true
});
}
} else {
- payload.value = {};
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
+ let unrecognized;
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__")
continue;
@@ -3228,6 +3614,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
if (keyResult.issues.length) {
if (def.mode === "loose") {
payload.value[key] = input[key];
+ } else if (values) {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
} else {
payload.issues.push({
code: "invalid_key",
@@ -3240,21 +3629,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
}
continue;
}
+ const outKey = keyResult.value;
+ if (outKey === "__proto__")
+ continue;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
if (result.issues.length) {
payload.issues.push(...prefixIssues(key, result.issues));
}
- payload.value[keyResult.value] = result.value;
+ payload.value[outKey] = result.value;
}));
} else {
if (result.issues.length) {
payload.issues.push(...prefixIssues(key, result.issues));
}
- payload.value[keyResult.value] = result.value;
+ payload.value[outKey] = result.value;
}
}
+ if (unrecognized && unrecognized.length > 0) {
+ payload.issues.push({
+ code: "unrecognized_keys",
+ input,
+ inst,
+ keys: unrecognized,
+ continue: true
+ });
+ }
}
if (proms.length) {
return Promise.all(proms).then(() => payload);
@@ -3267,7 +3668,10 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
const values = getEnumValues(def.entries);
const valuesSet = new Set(values);
inst._zod.values = valuesSet;
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k));
+ return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$");
+ });
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (valuesSet.has(input)) {
@@ -3284,12 +3688,12 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
});
var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
$ZodType.init(inst, def);
- if (def.values.length === 0) {
- throw new Error("Cannot create literal schema with no valid values");
- }
const values = new Set(def.values);
inst._zod.values = values;
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const vals = zod.def.values;
+ return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$");
+ });
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (values.has(input)) {
@@ -3307,6 +3711,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
+ globalConfig.memoizer?.guard(inst);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
throw new $ZodEncodeError(inst.constructor.name);
@@ -3316,7 +3721,6 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) =>
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
return output.then((output) => {
payload.value = output;
- payload.fallback = true;
return payload;
});
}
@@ -3324,59 +3728,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) =>
throw new $ZodAsyncError;
}
payload.value = _out;
- payload.fallback = true;
return payload;
};
});
-function handleOptionalResult(result, input) {
- if (input === undefined && (result.issues.length || result.fallback)) {
- return { issues: [], value: undefined };
- }
- return result;
+function handleOptionalResult(payload, result) {
+ payload.value = result.issues.length ? undefined : result.value;
+ return payload;
}
var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
inst._zod.optout = "optional";
- defineLazy(inst._zod, "values", () => {
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
+ defineLazyInternal(inst, "values", (zod) => {
+ const values = zod.def.innerType._zod.values;
+ return values ? new Set([...values, undefined]) : undefined;
});
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def.innerType._zod.pattern;
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
});
inst._zod.parse = (payload, ctx) => {
- if (def.innerType._zod.optin === "optional") {
- const input = payload.value;
- const result = def.innerType._zod.run(payload, ctx);
- if (result instanceof Promise)
- return result.then((r) => handleOptionalResult(r, input));
- return handleOptionalResult(result, input);
- }
if (payload.value === undefined) {
- return payload;
+ if (def.innerType._zod.optin !== "defaulted")
+ return payload;
+ const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ return result.then((result) => handleOptionalResult(payload, result));
+ return handleOptionalResult(payload, result);
}
return def.innerType._zod.run(payload, ctx);
};
});
var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
$ZodOptional.init(inst, def);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
- defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
+ defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern);
inst._zod.parse = (payload, ctx) => {
return def.innerType._zod.run(payload, ctx);
};
});
var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def.innerType._zod.pattern;
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
});
- defineLazy(inst._zod, "values", () => {
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
+ defineLazyInternal(inst, "values", (zod) => {
+ return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === null)
@@ -3386,8 +3786,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
});
var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.optin = "defaulted";
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -3411,8 +3811,8 @@ function handleDefaultResult(payload, def) {
}
var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.optin = "defaulted";
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -3425,8 +3825,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
});
var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "values", () => {
- const v = def.innerType._zod.values;
+ defineLazyInternal(inst, "values", (zod) => {
+ const v = zod.def.innerType._zod.values;
return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
});
inst._zod.parse = (payload, ctx) => {
@@ -3448,54 +3848,45 @@ function handleNonOptionalResult(payload, inst) {
}
return payload;
}
+function handleCatchResult(payload, result, def, ctx) {
+ if (!result.issues.length) {
+ payload.value = result.value;
+ if (result.memo)
+ payload.memo = true;
+ return payload;
+ }
+ payload.value = def.catchValue({
+ ...result,
+ value: payload.value,
+ error: {
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ },
+ input: payload.value
+ });
+ return payload;
+}
var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
}
- const result = def.innerType._zod.run(payload, ctx);
+ const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
if (result instanceof Promise) {
- return result.then((result) => {
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- payload.fallback = true;
- }
- return payload;
- });
- }
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- payload.fallback = true;
+ return result.then((result) => handleCatchResult(payload, result, def, ctx));
}
- return payload;
+ return handleCatchResult(payload, result, def, ctx);
};
});
var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "values", () => def.in._zod.values);
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
+ defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
const right = def.out._zod.run(payload, ctx);
@@ -3512,21 +3903,21 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
};
});
function handlePipeResult(left, next, ctx) {
- if (left.issues.length) {
+ if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
left.aborted = true;
return left;
}
- return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
}
var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
$ZodPipe.init(inst, def);
});
var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
- defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
- defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -3539,7 +3930,8 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
};
});
function handleReadonlyResult(payload) {
- payload.value = Object.freeze(payload.value);
+ if (!payload.memo)
+ payload.value = Object.freeze(payload.value);
return payload;
}
var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
@@ -3572,11 +3964,399 @@ function handleRefineResult(result, payload, input, inst) {
payload.issues.push(issue(_iss));
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/registries.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/memoizer.js
+class $ZodCyclicError extends Error {
+ constructor() {
+ super(`Cannot parse a reference cycle that closes through a transform`);
+ this.name = "ZodCyclicError";
+ }
+}
+var STATE = "~memo";
+var NO_ISSUES = [];
+function isRef(value) {
+ return value !== null && typeof value === "object";
+}
+function cloneIssues(issues) {
+ return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
+}
+var recursive = /* @__PURE__ */ new WeakMap;
+var NONE = 0;
+var ASSUMED = 1;
+var PROVEN = 2;
+function isRecursive(inst, stack, resolve) {
+ const cached = recursive.get(inst);
+ if (cached !== undefined)
+ return cached ? PROVEN : NONE;
+ if (stack.has(inst))
+ return PROVEN;
+ stack.add(inst);
+ let result = NONE;
+ const check = (child) => {
+ if (result !== PROVEN && child?._zod) {
+ const answer = isRecursive(child, stack, resolve);
+ if (answer > result)
+ result = answer;
+ }
+ };
+ const shape = (sh, spread) => {
+ let answer = NONE;
+ for (const key of Reflect.ownKeys(sh)) {
+ const desc = Object.getOwnPropertyDescriptor(sh, key);
+ if (spread && !desc.enumerable)
+ continue;
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
+ if (child > answer)
+ answer = child;
+ }
+ return answer;
+ };
+ const merge = (answer) => {
+ if (answer > result)
+ result = answer;
+ };
+ const def = inst._zod.def;
+ const kind = def.type;
+ switch (kind) {
+ case "object": {
+ const raw = rawShape(def);
+ merge(raw ? shape(raw, true) : ASSUMED);
+ check(def.catchall);
+ break;
+ }
+ case "array":
+ check(def.element);
+ break;
+ case "tuple":
+ for (const el of def.items)
+ check(el);
+ check(def.rest);
+ break;
+ case "record":
+ case "map":
+ check(def.keyType);
+ check(def.valueType);
+ break;
+ case "set":
+ check(def.valueType);
+ break;
+ case "union":
+ for (const el of def.options)
+ check(el);
+ break;
+ case "intersection":
+ check(def.left);
+ check(def.right);
+ break;
+ case "optional":
+ case "nullable":
+ case "default":
+ case "prefault":
+ case "catch":
+ case "readonly":
+ case "nonoptional":
+ case "promise":
+ case "success":
+ check(def.innerType);
+ break;
+ case "pipe":
+ check(def.in);
+ check(def.out);
+ break;
+ case "function":
+ check(def.input);
+ check(def.output);
+ break;
+ case "lazy": {
+ const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);
+ merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
+ break;
+ }
+ case "template_literal":
+ case "string":
+ case "number":
+ case "int":
+ case "boolean":
+ case "bigint":
+ case "symbol":
+ case "undefined":
+ case "null":
+ case "void":
+ case "never":
+ case "any":
+ case "unknown":
+ case "date":
+ case "nan":
+ case "enum":
+ case "literal":
+ case "file":
+ case "transform":
+ case "custom":
+ break;
+ default: {
+ for (const key in def) {
+ const desc = Object.getOwnPropertyDescriptor(def, key);
+ if (!desc || desc.get)
+ continue;
+ const value = desc.value;
+ if (!value || typeof value !== "object")
+ continue;
+ if (value._zod)
+ check(value);
+ else if (Array.isArray(value))
+ for (const el of value)
+ check(el);
+ }
+ }
+ }
+ stack.delete(inst);
+ return settle(inst, result);
+}
+function settle(inst, answer) {
+ if (answer !== ASSUMED)
+ recursive.set(inst, answer === PROVEN);
+ return answer;
+}
+function bucketFor(state, inst) {
+ let bucket = state.buckets.get(inst);
+ if (!bucket) {
+ bucket = new WeakMap;
+ state.buckets.set(inst, bucket);
+ }
+ return bucket;
+}
+var handoff;
+var open2 = [];
+var memo = {
+ alloc(_inst, payload, empty) {
+ const bucket = handoff;
+ if (!bucket)
+ return empty;
+ handoff = undefined;
+ const entry = { value: empty, issues: null };
+ bucket.set(payload.value, entry);
+ open2.push(entry);
+ return empty;
+ },
+ guard(inst) {
+ var _a;
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
+ inst._zod.deferred.push(() => {
+ const base = inst._zod.parse;
+ const wrapped = (payload, ctx) => {
+ if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value))
+ throw new $ZodCyclicError;
+ return base(payload, ctx);
+ };
+ inst._zod.parse = wrapped;
+ if (inst._zod.run === base)
+ inst._zod.run = wrapped;
+ });
+ },
+ attach(inst) {
+ var _a;
+ let isRecursiveInst;
+ let rechecked = false;
+ let lastCtx;
+ let lastBucket;
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
+ inst._zod.deferred.push(() => {
+ const base = inst._zod.parse;
+ const wrapped = (payload, ctx) => {
+ if (isRecursiveInst === undefined) {
+ const walked = isRecursive(inst, new Set, false);
+ if (walked === NONE) {
+ inst._zod.parse = base;
+ if (inst._zod.run === wrapped)
+ inst._zod.run = base;
+ return base(payload, ctx);
+ }
+ if (walked === PROVEN || rechecked)
+ isRecursiveInst = true;
+ else
+ rechecked = true;
+ }
+ const input = payload.value;
+ if (!isRef(input))
+ return base(payload, ctx);
+ let state = ctx[STATE];
+ if (!state) {
+ state = { buckets: new WeakMap, backEdges: undefined };
+ ctx[STATE] = state;
+ }
+ let bucket;
+ if (lastCtx === ctx) {
+ bucket = lastBucket;
+ } else {
+ bucket = bucketFor(state, inst);
+ lastCtx = ctx;
+ lastBucket = bucket;
+ }
+ const hit = bucket.get(input);
+ if (hit) {
+ payload.value = hit.value;
+ if (hit.issues) {
+ if (hit.issues.length)
+ payload.issues.push(...cloneIssues(hit.issues));
+ } else {
+ payload.memo = true;
+ state.backEdges ?? (state.backEdges = new WeakSet);
+ state.backEdges.add(hit.value);
+ }
+ return payload;
+ }
+ handoff = bucket;
+ const depth = open2.length;
+ const result = base(payload, ctx);
+ handoff = undefined;
+ const entry = open2.length > depth ? open2.pop() : undefined;
+ if (result instanceof Promise) {
+ return result.then((r) => {
+ if (entry)
+ entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
+ return r;
+ });
+ }
+ if (entry)
+ entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
+ return result;
+ };
+ inst._zod.parse = wrapped;
+ if (inst._zod.run === base)
+ inst._zod.run = wrapped;
+ });
+ }
+};
+function memoizer() {
+ return memo;
+}
+function isBackEdge(ctx, value) {
+ const backEdges = ctx[STATE]?.backEdges;
+ return backEdges !== undefined && isRef(value) && backEdges.has(value);
+}
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/locales/en.js
+var error = () => {
+ const Sizable = {
+ string: { unit: "characters", verb: "to have" },
+ file: { unit: "bytes", verb: "to have" },
+ array: { unit: "items", verb: "to have" },
+ set: { unit: "items", verb: "to have" },
+ map: { unit: "entries", verb: "to have" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ const FormatDictionary = {
+ regex: "input",
+ email: "email address",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO datetime",
+ date: "ISO date",
+ time: "ISO time",
+ duration: "ISO duration",
+ ipv4: "IPv4 address",
+ ipv6: "IPv6 address",
+ mac: "MAC address",
+ cidrv4: "IPv4 range",
+ cidrv6: "IPv6 range",
+ base64: "base64-encoded string",
+ base64url: "base64url-encoded string",
+ json_string: "JSON string",
+ e164: "E.164 number",
+ currency_code: "currency code",
+ credit_card: "credit card number",
+ iban: "IBAN",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ function getTypeName(type, input) {
+ if (type === "number" && typeof input === "number" && !Number.isFinite(input)) {
+ return String(input);
+ }
+ return TypeDictionary[type] ?? type;
+ }
+ return (issue) => {
+ switch (issue.code) {
+ case "invalid_type": {
+ const expected = getTypeName(issue.expected);
+ const receivedType = parsedType(issue.input);
+ const received = getTypeName(receivedType, issue.input);
+ return `Invalid input: expected ${expected}, received ${received}`;
+ }
+ case "invalid_value":
+ if (issue.values.length === 1)
+ return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
+ return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
+ case "too_big": {
+ const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue.origin);
+ if (sizing)
+ return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
+ return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue.origin);
+ if (sizing) {
+ return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue;
+ if (_issue.format === "starts_with") {
+ return `Invalid string: must start with "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Invalid string: must end with "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Invalid string: must include "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Invalid string: must match pattern ${_issue.pattern}`;
+ return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
+ }
+ case "not_multiple_of":
+ return `Invalid number: must be a multiple of ${issue.divisor}`;
+ case "unrecognized_keys":
+ return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
+ case "invalid_key":
+ return `Invalid key in ${issue.origin}`;
+ case "invalid_union":
+ if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
+ const opts = issue.options.map((o) => `'${o}'`).join(" | ");
+ return `Invalid discriminator value. Expected ${opts}`;
+ }
+ if (issue.inclusive === false) {
+ return "Invalid input: more than one option matched";
+ }
+ return "Invalid input";
+ case "invalid_element":
+ return `Invalid value in ${issue.origin}`;
+ default:
+ return `Invalid input`;
+ }
+ };
+};
+function en_default() {
+ return {
+ localeError: error()
+ };
+}
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/registries.js
var _a2;
-var $output = Symbol("ZodOutput");
-var $input = Symbol("ZodInput");
-
class $ZodRegistry {
constructor() {
this._map = new WeakMap;
@@ -3622,12 +4402,14 @@ function registry() {
}
(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
var globalRegistry = globalThis.__zod_globalRegistry;
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/api.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/api.js
+function snapshotChecks(def) {
+ if (def.checks)
+ def.checks = [...def.checks];
+ return def;
+}
function _string(Class, params) {
- return new Class({
- type: "string",
- ...normalizeParams(params)
- });
+ return new Class(snapshotChecks({ type: "string", ...normalizeParams(params) }));
}
function _email(Class, params) {
return new Class({
@@ -3867,11 +4649,7 @@ function _isoDuration(Class, params) {
});
}
function _number(Class, params) {
- return new Class({
- type: "number",
- checks: [],
- ...normalizeParams(params)
- });
+ return new Class(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) }));
}
function _int(Class, params) {
return new Class({
@@ -4053,7 +4831,8 @@ function _superRefine(fn, params) {
if (_issue.fatal)
_issue.continue = false;
_issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
+ if (!("input" in _issue))
+ _issue.input = payload.value;
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
@@ -4071,7 +4850,17 @@ function _check(fn, params) {
ch._zod.check = fn;
return ch;
}
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/to-json-schema.js
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/to-json-schema.js
+function assignProps(target, ...sources) {
+ for (const source of sources) {
+ for (const key of Reflect.ownKeys(source)) {
+ if (Object.prototype.propertyIsEnumerable.call(source, key)) {
+ assignProp(target, key, source[key]);
+ }
+ }
+ }
+ return target;
+}
function initializeContext(params) {
let target = params?.target ?? "draft-2020-12";
if (target === "draft-4")
@@ -4087,12 +4876,25 @@ function initializeContext(params) {
io: params?.io ?? "output",
counter: 0,
seen: new Map,
+ sharedDefsExtractedFor: undefined,
+ sharedEmitDoneFor: undefined,
cycles: params?.cycles ?? "ref",
reused: params?.reused ?? "inline",
+ intersections: [],
+ deferred: [],
external: params?.external ?? undefined
};
}
-function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
+function handleUnrepresentable(schema, ctx, json, params, message) {
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) : ctx.unrepresentable;
+ if (result === "any")
+ return false;
+ if (result === undefined || result === "throw")
+ throw new Error(message);
+ Object.assign(json, result);
+ return true;
+}
+function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {
var _a;
const def = schema._zod.def;
const seen = ctx.seen.get(schema);
@@ -4106,6 +4908,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
}
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
ctx.seen.set(schema, result);
+ ctx.sharedDefsExtractedFor = undefined;
+ ctx.sharedEmitDoneFor = undefined;
const overrideSchema = schema._zod.toJSONSchema?.();
if (overrideSchema) {
result.schema = overrideSchema;
@@ -4129,13 +4933,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
if (parent) {
if (!result.ref)
result.ref = parent;
- process2(parent, ctx, params);
+ processSchema(parent, ctx, params);
ctx.seen.get(parent).isParent = true;
}
}
const meta = ctx.metadataRegistry.get(schema);
if (meta)
- Object.assign(result.schema, meta);
+ assignProps(result.schema, meta);
if (ctx.io === "input" && isTransforming(schema)) {
delete result.schema.examples;
delete result.schema.default;
@@ -4146,10 +4950,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
const _result = ctx.seen.get(schema);
return _result.schema;
}
+function encodeJSONPointerSegment(segment) {
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
+}
function extractDefs(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root)
throw new Error("Unprocessed schema. This is a bug in Zod.");
+ if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)
+ return;
const idToSchema = new Map;
for (const entry of ctx.seen.entries()) {
const id = ctx.metadataRegistry.get(entry[0])?.id;
@@ -4171,15 +4980,15 @@ function extractDefs(ctx, schema) {
}
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
entry[1].defId = id;
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
- }
- if (entry[1] === root) {
- return { ref: "#" };
+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };
}
const uriPrefix = `#`;
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
+ if (entry[1] === root && !entry[1].schema.id) {
+ return { ref: uriPrefix };
+ }
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
- return { defId, ref: defUriPrefix + defId };
+ return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };
};
const extractToDef = (entry) => {
if (entry[1].schema.$ref) {
@@ -4229,10 +5038,119 @@ function extractDefs(ctx, schema) {
if (seen.count > 1) {
if (ctx.reused === "ref") {
extractToDef(entry);
+ }
+ }
+ }
+ if (ctx.external)
+ ctx.sharedDefsExtractedFor = ctx.external;
+}
+function compactTypeUnion(schema) {
+ const options = schema.anyOf;
+ if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)
+ return;
+ const types = [];
+ for (const option of options) {
+ if (!option || typeof option !== "object")
+ return;
+ compactTypeUnion(option);
+ const keys = Object.keys(option);
+ if (keys.length !== 1 || keys[0] !== "type")
+ return;
+ const type = option.type;
+ for (const member of Array.isArray(type) ? type : [type]) {
+ if (typeof member !== "string")
+ return;
+ if (!types.includes(member))
+ types.push(member);
+ }
+ }
+ delete schema.anyOf;
+ schema.type = types.length === 1 ? types[0] : types;
+}
+var FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]);
+var UNION_KEYS = ["oneOf", "anyOf"];
+function undeclaredConstraint(member) {
+ const extra = member.additionalProperties;
+ if (extra === undefined || extra === false || typeof extra !== "object" || extra === null)
+ return null;
+ return Object.keys(extra).length ? extra : null;
+}
+function foldObjects(members) {
+ const objects = [];
+ for (const member of members) {
+ if (typeof member !== "object" || member.type !== "object")
+ return null;
+ for (const key in member) {
+ if (!FOLDABLE_KEYS.has(key))
+ return null;
+ }
+ objects.push(member);
+ }
+ const properties = {};
+ const required = new Set;
+ for (const object of objects) {
+ for (const key in object.properties) {
+ if (Object.prototype.hasOwnProperty.call(properties, key))
continue;
+ const parts = [];
+ for (const other of objects) {
+ const part = other.properties?.[key] ?? undeclaredConstraint(other);
+ if (part === null || part === undefined)
+ continue;
+ if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))
+ parts.push(part);
}
+ const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
+ assignProp(properties, key, merged);
}
+ for (const key of object.required ?? [])
+ required.add(key);
+ }
+ const folded = { type: "object", properties };
+ if (required.size)
+ folded.required = [...required];
+ if (objects.every((object) => object.additionalProperties === false)) {
+ folded.additionalProperties = false;
+ } else {
+ const constraints = [];
+ for (const object of objects) {
+ const constraint = undeclaredConstraint(object);
+ if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
+ constraints.push(constraint);
+ }
+ if (constraints.length === 1)
+ folded.additionalProperties = constraints[0];
+ else if (constraints.length > 1)
+ folded.additionalProperties = { allOf: constraints };
+ }
+ return folded;
+}
+function foldIntersection(json) {
+ const allOf = json.allOf;
+ if (!Array.isArray(allOf) || allOf.length < 2)
+ return;
+ for (const key of FOLDABLE_KEYS)
+ if (key in json)
+ return;
+ const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));
+ let folded = null;
+ if (!unions.length) {
+ folded = foldObjects(allOf);
+ } else {
+ const union = unions[0];
+ const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));
+ if (Object.keys(union).length !== 1)
+ return;
+ const rest = allOf.filter((m) => m !== union);
+ const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));
+ if (branches.some((b) => !b))
+ return;
+ folded = { [keyword]: branches };
}
+ if (!folded)
+ return;
+ delete json.allOf;
+ assignProps(json, folded);
}
function finalize(ctx, schema) {
const root = ctx.seen.get(schema);
@@ -4254,9 +5172,9 @@ function finalize(ctx, schema) {
schema.allOf = schema.allOf ?? [];
schema.allOf.push(refSchema);
} else {
- Object.assign(schema, refSchema);
+ assignProps(schema, refSchema);
}
- Object.assign(schema, _cached);
+ assignProps(schema, _cached);
const isParentRef = zodSchema._zod.parent === ref;
if (isParentRef) {
for (const key in schema) {
@@ -4300,8 +5218,36 @@ function finalize(ctx, schema) {
path: seen.path ?? []
});
};
- for (const entry of [...ctx.seen.entries()].reverse()) {
- flattenRef(entry[0]);
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
+ for (const entry of [...ctx.seen.entries()].reverse()) {
+ flattenRef(entry[0]);
+ }
+ if (ctx.target !== "openapi-3.0") {
+ for (const entry of ctx.seen.entries()) {
+ compactTypeUnion(entry[1].def ?? entry[1].schema);
+ }
+ }
+ for (const rewrite of ctx.deferred)
+ rewrite();
+ if (ctx.intersections.length) {
+ const carriers = new Map;
+ for (const seen of ctx.seen.values()) {
+ for (const json of [seen.schema, seen.def]) {
+ const allOf = json?.allOf;
+ if (!Array.isArray(allOf))
+ continue;
+ const existing = carriers.get(allOf);
+ if (existing)
+ existing.push(json);
+ else
+ carriers.set(allOf, [json]);
+ }
+ }
+ for (const allOf of ctx.intersections) {
+ for (const json of carriers.get(allOf) ?? [])
+ foldIntersection(json);
+ }
+ }
}
const result = {};
if (ctx.target === "draft-2020-12") {
@@ -4317,19 +5263,23 @@ function finalize(ctx, schema) {
throw new Error("Schema is missing an `id` property");
result.$id = ctx.external.uri(id);
}
- Object.assign(result, root.def ?? root.schema);
+ assignProps(result, root.defId ? root.schema : root.def ?? root.schema);
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
if (rootMetaId !== undefined && result.id === rootMetaId)
delete result.id;
const defs = ctx.external?.defs ?? {};
- for (const entry of ctx.seen.entries()) {
- const seen = entry[1];
- if (seen.def && seen.defId) {
- if (seen.def.id === seen.defId)
- delete seen.def.id;
- defs[seen.defId] = seen.def;
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
+ for (const entry of ctx.seen.entries()) {
+ const seen = entry[1];
+ if (seen.def && seen.defId) {
+ if (seen.def.id === seen.defId)
+ delete seen.def.id;
+ assignProp(defs, seen.defId, seen.def);
+ }
}
}
+ if (ctx.external)
+ ctx.sharedEmitDoneFor = ctx.external;
if (ctx.external) {} else {
if (Object.keys(defs).length > 0) {
if (ctx.target === "draft-2020-12") {
@@ -4371,7 +5321,7 @@ function isTransforming(_schema, _ctx) {
return isTransforming(def.valueType, ctx);
if (def.type === "lazy")
return isTransforming(def.getter(), ctx);
- if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") {
return isTransforming(def.innerType, ctx);
}
if (def.type === "intersection") {
@@ -4412,29 +5362,122 @@ function isTransforming(_schema, _ctx) {
}
var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
const ctx = initializeContext({ ...params, processors });
- process2(schema, ctx);
+ processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
const { libraryOptions, target } = params ?? {};
const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
- process2(schema, ctx);
+ processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema-processors.js
-var formatMap = {
- guid: "uuid",
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema-processors.js
+var narrowMin = (agg, key, value) => {
+ if (agg[key] === undefined || value > agg[key])
+ agg[key] = value;
+};
+var narrowMax = (agg, key, value) => {
+ if (agg[key] === undefined || value < agg[key])
+ agg[key] = value;
+};
+var narrowBoth = (agg, value) => {
+ narrowMin(agg, "minimum", value);
+ narrowMax(agg, "maximum", value);
+};
+var addDivisor = (agg, value) => {
+ agg.multipleOf ?? (agg.multipleOf = []);
+ if (!agg.multipleOf.includes(value))
+ agg.multipleOf.push(value);
+};
+var addPattern = (agg, pattern) => {
+ agg.patterns ?? (agg.patterns = new Set);
+ agg.patterns.add(pattern);
+};
+var intersectMime = (agg, mime) => {
+ agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
+};
+var setFormat = (agg, format) => {
+ agg.format = format;
+ if (format.includes("int"))
+ agg.isInt = true;
+};
+var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum);
+var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum);
+var formatContributor = (ranges) => (agg, def) => {
+ setFormat(agg, def.format);
+ const [minimum, maximum] = ranges[def.format];
+ narrowMin(agg, "minimum", minimum);
+ narrowMax(agg, "maximum", maximum);
+};
+var contributors = {
+ greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
+ less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
+ multiple_of: (agg, def) => addDivisor(agg, def.value),
+ number_format: formatContributor(NUMBER_FORMAT_RANGES),
+ bigint_format: formatContributor(BIGINT_FORMAT_RANGES),
+ min_length: minContributor,
+ max_length: maxContributor,
+ length_equals: (agg, def) => narrowBoth(agg, def.length),
+ min_size: minContributor,
+ max_size: maxContributor,
+ size_equals: (agg, def) => narrowBoth(agg, def.size),
+ string_format: (agg, def) => {
+ setFormat(agg, def.format);
+ if (def.pattern)
+ addPattern(agg, def.pattern);
+ if (def.format === "base64" || def.format === "base64url")
+ agg.contentEncoding = def.format;
+ if (def.local || def.precision === -1)
+ agg.laxFormat = true;
+ },
+ mime_type: (agg, def) => intersectMime(agg, def.mime)
+};
+function aggregateChecks(schema) {
+ const agg = {};
+ const def = schema._zod.def;
+ const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
+ for (const ch of list)
+ contributors[ch._zod.def.check]?.(agg, ch._zod.def);
+ const bag = schema._zod.bag;
+ if (bag.minimum !== undefined)
+ narrowMin(agg, "minimum", bag.minimum);
+ if (bag.exclusiveMinimum !== undefined)
+ narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
+ if (bag.maximum !== undefined)
+ narrowMax(agg, "maximum", bag.maximum);
+ if (bag.exclusiveMaximum !== undefined)
+ narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
+ if (bag.multipleOf !== undefined)
+ addDivisor(agg, bag.multipleOf);
+ if (bag.format !== undefined) {
+ agg.format ?? (agg.format = bag.format);
+ if (bag.format.includes("int"))
+ agg.isInt = true;
+ }
+ if (bag.mime)
+ intersectMime(agg, bag.mime);
+ for (const pattern of bag.patterns ?? [])
+ addPattern(agg, pattern);
+ return agg;
+}
+var formatMap = {
+ guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: ""
};
+var exactPatterns = new Map([
+ [base64Charset, base64],
+ [base64urlCharset, base64url]
+]);
+var exactPattern = (p) => exactPatterns.get(p) ?? p;
var stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
- const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minLength = minimum;
if (typeof maximum === "number")
@@ -4443,19 +5486,19 @@ var stringProcessor = (schema, ctx, _json, _params) => {
json.format = formatMap[format] ?? format;
if (json.format === "")
delete json.format;
- if (format === "time") {
+ if (format === "time" || laxFormat) {
delete json.format;
}
}
if (contentEncoding)
json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
- const regexes = [...patterns];
- if (regexes.length === 1)
- json.pattern = regexes[0].source;
- else if (regexes.length > 1) {
+ const patternList = [...patterns].map(exactPattern);
+ if (patternList.length === 1)
+ json.pattern = patternList[0].source;
+ else if (patternList.length > 1) {
json.allOf = [
- ...regexes.map((regex) => ({
+ ...patternList.map((regex) => ({
...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
pattern: regex.source
}))
@@ -4463,13 +5506,10 @@ var stringProcessor = (schema, ctx, _json, _params) => {
}
}
};
-var numberProcessor = (schema, ctx, _json, _params) => {
+var numberProcessor = (schema, ctx, _json, params) => {
const json = _json;
- const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
- if (typeof format === "string" && format.includes("int"))
- json.type = "integer";
- else
- json.type = "number";
+ const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
+ json.type = isInt ? "integer" : "number";
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
@@ -4493,8 +5533,20 @@ var numberProcessor = (schema, ctx, _json, _params) => {
} else if (typeof maximum === "number") {
json.maximum = maximum;
}
- if (typeof multipleOf === "number")
- json.multipleOf = multipleOf;
+ if (multipleOf) {
+ const divisors = new Set;
+ for (const divisor of multipleOf) {
+ if (Number.isFinite(divisor) && divisor !== 0)
+ divisors.add(Math.abs(divisor));
+ else
+ handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
+ }
+ const [first, ...rest] = divisors;
+ if (first !== undefined)
+ json.multipleOf = first;
+ if (rest.length)
+ json.allOf = [...json.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
+ }
};
var booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
@@ -4506,26 +5558,31 @@ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
var enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = getEnumValues(def.entries);
+ if (values.length === 0) {
+ json.not = {};
+ return;
+ }
if (values.every((v) => typeof v === "number"))
json.type = "number";
if (values.every((v) => typeof v === "string"))
json.type = "string";
json.enum = values;
};
-var literalProcessor = (schema, ctx, json, _params) => {
+var literalProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
+ if (def.values.length === 0) {
+ json.not = {};
+ return;
+ }
const vals = [];
for (const val of def.values) {
if (val === undefined) {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Literal `undefined` cannot be represented in JSON Schema");
- }
+ if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema"))
+ return;
} else if (typeof val === "bigint") {
- if (ctx.unrepresentable === "throw") {
- throw new Error("BigInt literals cannot be represented in JSON Schema");
- } else {
- vals.push(Number(val));
- }
+ if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema"))
+ return;
+ vals.push(Number(val));
} else {
vals.push(val);
}
@@ -4550,53 +5607,61 @@ var literalProcessor = (schema, ctx, json, _params) => {
json.enum = vals;
}
};
-var customProcessor = (_schema, ctx, _json, _params) => {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Custom types cannot be represented in JSON Schema");
- }
+var customProcessor = (schema, ctx, json, params) => {
+ handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
};
-var transformProcessor = (_schema, ctx, _json, _params) => {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Transforms cannot be represented in JSON Schema");
- }
+var transformProcessor = (schema, ctx, json, params) => {
+ handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
};
var arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
- const { minimum, maximum } = schema._zod.bag;
+ const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
- json.items = process2(def.element, ctx, {
+ json.items = processSchema(def.element, ctx, {
...params,
path: [...params.path, "items"]
});
};
+function inputOptin(schema) {
+ const def = schema._zod.def;
+ if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) {
+ return inputOptin(def.out);
+ }
+ if (def.type === "catch") {
+ return inputOptin(def.innerType);
+ }
+ return schema._zod.optin;
+}
var objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
+ const shape = def.shape;
+ const symbolKeys = Object.getOwnPropertySymbols(shape);
+ if (symbolKeys.length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) {
+ return;
+ }
json.type = "object";
json.properties = {};
- const shape = def.shape;
for (const key in shape) {
- json.properties[key] = process2(shape[key], ctx, {
+ assignProp(json.properties, key, processSchema(shape[key], ctx, {
...params,
path: [...params.path, "properties", key]
- });
+ }));
}
- const allKeys = new Set(Object.keys(shape));
- const requiredKeys = new Set([...allKeys].filter((key) => {
- const v = def.shape[key]._zod;
- if (ctx.io === "input") {
- return v.optin === undefined;
- } else {
- return v.optout === undefined;
+ const requiredKeys = [];
+ for (const key of Object.keys(shape)) {
+ const field = def.shape[key];
+ if (ctx.io === "input" ? inputOptin(field) === undefined : field._zod.optout === undefined) {
+ requiredKeys.push(key);
}
- }));
- if (requiredKeys.size > 0) {
- json.required = Array.from(requiredKeys);
+ }
+ if (requiredKeys.length > 0) {
+ json.required = requiredKeys;
}
if (def.catchall?._zod.def.type === "never") {
json.additionalProperties = false;
@@ -4604,7 +5669,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
if (ctx.io === "output")
json.additionalProperties = false;
} else if (def.catchall) {
- json.additionalProperties = process2(def.catchall, ctx, {
+ json.additionalProperties = processSchema(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
@@ -4613,7 +5678,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
var unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const isExclusive = def.inclusive === false;
- const options = def.options.map((x, i) => process2(x, ctx, {
+ const options = def.options.map((x, i) => processSchema(x, ctx, {
...params,
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
}));
@@ -4625,11 +5690,11 @@ var unionProcessor = (schema, ctx, json, params) => {
};
var intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- const a = process2(def.left, ctx, {
+ const a = processSchema(def.left, ctx, {
...params,
path: [...params.path, "allOf", 0]
});
- const b = process2(def.right, ctx, {
+ const b = processSchema(def.right, ctx, {
...params,
path: [...params.path, "allOf", 1]
});
@@ -4639,46 +5704,117 @@ var intersectionProcessor = (schema, ctx, json, params) => {
...isSimpleIntersection(b) ? b.allOf : [b]
];
json.allOf = allOf;
+ ctx.intersections.push(allOf);
};
+function stringifyKeyNames(bySchema, json, visited) {
+ if (json.$ref) {
+ if (visited.has(json))
+ return json;
+ visited.add(json);
+ const def = bySchema.get(json)?.def;
+ if (!def)
+ return json;
+ const inlined = stringifyKeyNames(bySchema, def, visited);
+ return inlined === def ? json : inlined;
+ }
+ for (const keyword of ["anyOf", "oneOf"]) {
+ const branches = json[keyword];
+ if (!Array.isArray(branches))
+ continue;
+ const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
+ if (mapped.some((branch, i) => branch !== branches[i]))
+ json = { ...json, [keyword]: mapped };
+ }
+ const types = Array.isArray(json.type) ? json.type : [json.type];
+ const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
+ const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);
+ if (!numericType && !values?.some((v) => typeof v === "number"))
+ return json;
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
+ if (rest.enum)
+ rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
+ else if (typeof rest.const === "number")
+ rest.const = String(rest.const);
+ if (!numericType)
+ return rest;
+ rest.type = "string";
+ if (!values)
+ rest.pattern = (types.includes("number") ? number : integer).source;
+ return rest;
+}
+var pendingRecords = new WeakMap;
+function rewriteKeyNames(ctx) {
+ const bySchema = new Map;
+ for (const entry of ctx.seen.values()) {
+ if (entry.def && !bySchema.has(entry.schema))
+ bySchema.set(entry.schema, entry);
+ }
+ const rewrites = new Map;
+ for (const record of pendingRecords.get(ctx) ?? []) {
+ const seen = ctx.seen.get(record);
+ const names = (seen?.def ?? seen?.schema)?.propertyNames;
+ if (!names || names === true || rewrites.has(names))
+ continue;
+ const rewritten = stringifyKeyNames(bySchema, names, new Set);
+ if (rewritten !== names)
+ rewrites.set(names, rewritten);
+ }
+ if (!rewrites.size)
+ return;
+ for (const entry of ctx.seen.values()) {
+ for (const carrier of [entry.schema, entry.def]) {
+ const rewritten = carrier && rewrites.get(carrier.propertyNames);
+ if (rewritten)
+ carrier.propertyNames = rewritten;
+ }
+ }
+}
var recordProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "object";
const keyType = def.keyType;
- const keyBag = keyType._zod.bag;
- const patterns = keyBag?.patterns;
+ const patterns = aggregateChecks(keyType).patterns;
if (def.mode === "loose" && patterns && patterns.size > 0) {
- const valueSchema = process2(def.valueType, ctx, {
+ const valueSchema = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "patternProperties", "*"]
});
json.patternProperties = {};
for (const pattern of patterns) {
- json.patternProperties[pattern.source] = valueSchema;
+ assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
}
} else {
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
- json.propertyNames = process2(def.keyType, ctx, {
+ json.propertyNames = processSchema(def.keyType, ctx, {
...params,
path: [...params.path, "propertyNames"]
});
+ let pending = pendingRecords.get(ctx);
+ if (!pending) {
+ pending = [];
+ pendingRecords.set(ctx, pending);
+ ctx.deferred.push(() => rewriteKeyNames(ctx));
+ }
+ pending.push(schema);
}
- json.additionalProperties = process2(def.valueType, ctx, {
+ json.additionalProperties = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
}
const keyValues = keyType._zod.values;
- if (keyValues) {
+ const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined;
+ if (keyValues && !def.partial && !omittableOnInput) {
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
if (validKeyValues.length > 0) {
- json.required = validKeyValues;
+ json.required = validKeyValues.map(String);
}
}
};
var nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- const inner = process2(def.innerType, ctx, params);
+ const inner = processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
@@ -4689,35 +5825,55 @@ var nullableProcessor = (schema, ctx, json, params) => {
};
var nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
- process2(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
+var UNREPRESENTABLE_DEFAULT = Symbol();
+function serializeDefaultValue(value, schema, ctx, json, params) {
+ let unrepresentable = false;
+ const serialized = JSON.stringify(value, (_, val) => {
+ if (typeof val !== "bigint")
+ return val;
+ unrepresentable = true;
+ return null;
+ });
+ if (!unrepresentable)
+ return JSON.parse(serialized);
+ handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
+ return UNREPRESENTABLE_DEFAULT;
+}
var defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process2(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
- json.default = JSON.parse(JSON.stringify(def.defaultValue));
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
+ if (value !== UNREPRESENTABLE_DEFAULT)
+ json.default = value;
};
var prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process2(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
- if (ctx.io === "input")
- json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
+ if (ctx.io !== "input")
+ return;
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
+ if (value !== UNREPRESENTABLE_DEFAULT)
+ json._prefault = value;
};
var catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process2(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(undefined);
} catch {
- throw new Error("Dynamic catch values are not supported in JSON Schema");
+ handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
+ return;
}
json.default = catchValue;
};
@@ -4725,92 +5881,73 @@ var pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
- process2(innerType, ctx, params);
+ processSchema(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process2(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
};
var optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
- process2(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/iso.js
-var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
- $ZodISODateTime.init(inst, def);
- ZodStringFormat.init(inst, def);
-});
-function datetime2(params) {
- return _isoDateTime(ZodISODateTime, params);
-}
-var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
- $ZodISODate.init(inst, def);
- ZodStringFormat.init(inst, def);
-});
-function date2(params) {
- return _isoDate(ZodISODate, params);
-}
-var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
- $ZodISOTime.init(inst, def);
- ZodStringFormat.init(inst, def);
-});
-function time2(params) {
- return _isoTime(ZodISOTime, params);
-}
-var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
- $ZodISODuration.init(inst, def);
- ZodStringFormat.init(inst, def);
-});
-function duration2(params) {
- return _isoDuration(ZodISODuration, params);
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/errors.js
+var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
+function _lazyMethod(proto, key, make) {
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const value = make(this);
+ Object.defineProperty(this, key, { value, configurable: true, writable: true });
+ return value;
+ },
+ set(value) {
+ Object.defineProperty(this, key, { value, configurable: true, writable: true });
+ }
+ });
}
-
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/errors.js
var initializer2 = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
- Object.defineProperties(inst, {
- format: {
- value: (mapper) => formatError(inst, mapper)
- },
- flatten: {
- value: (mapper) => flattenError(inst, mapper)
- },
- addIssue: {
- value: (issue) => {
- inst.issues.push(issue);
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
- }
- },
- addIssues: {
- value: (issues) => {
- inst.issues.push(...issues);
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
- }
- },
- isEmpty: {
- get() {
- return inst.issues.length === 0;
- }
+ const proto = Object.getPrototypeOf(inst);
+ if (_installedErrorProtos.has(proto))
+ return;
+ _installedErrorProtos.add(proto);
+ _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper));
+ _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper));
+ _lazyMethod(proto, "addIssue", (self) => (issue) => {
+ self.issues.push(issue);
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
+ });
+ _lazyMethod(proto, "addIssues", (self) => (issues) => {
+ self.issues.push(...issues);
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
+ });
+ Object.defineProperty(proto, "isEmpty", {
+ configurable: true,
+ enumerable: false,
+ get() {
+ return this.issues.length === 0;
}
});
};
-var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
+var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, undefined, {
Parent: Error
});
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/parse.js
-var parse3 = /* @__PURE__ */ _parse(ZodRealError);
-var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
-var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
-var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/parse.js
+var parse2 = /* @__PURE__ */ _parse(ZodRealError);
+var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
+var safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
+var safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
var encode = /* @__PURE__ */ _encode(ZodRealError);
var decode = /* @__PURE__ */ _decode(ZodRealError);
var encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
@@ -4820,259 +5957,323 @@ var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
-// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/schemas.js
-var _installedGroups = /* @__PURE__ */ new WeakMap;
-function _installLazyMethods(inst, group, methods) {
- const proto = Object.getPrototypeOf(inst);
- let installed = _installedGroups.get(proto);
- if (!installed) {
- installed = new Set;
- _installedGroups.set(proto, installed);
- }
- if (installed.has(group))
- return;
- installed.add(group);
- for (const key in methods) {
- const fn = methods[key];
- Object.defineProperty(proto, key, {
- configurable: true,
- enumerable: false,
- get() {
- const bound = fn.bind(this);
- Object.defineProperty(this, key, {
- configurable: true,
- writable: true,
- enumerable: true,
- value: bound
- });
- return bound;
- },
- set(v) {
- Object.defineProperty(this, key, {
- configurable: true,
- writable: true,
- enumerable: true,
- value: v
- });
- }
- });
- }
+// ../../../node_modules/.bun/[email protected]/node_modules/zod/v4/classic/schemas.js
+function _ensureDefaultLocale() {
+ if (!globalConfig.localeError)
+ config(en_default());
+}
+function _ensureDefaultMemoizer() {
+ if (!globalConfig.memoizer)
+ config({ memoizer: memoizer() });
}
var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
+ _ensureDefaultLocale();
$ZodType.init(inst, def);
- Object.assign(inst["~standard"], {
- jsonSchema: {
- input: createStandardJSONSchemaMethod(inst, "input"),
- output: createStandardJSONSchemaMethod(inst, "output")
- }
- });
- inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
inst.def = def;
inst.type = def.type;
- Object.defineProperty(inst, "_def", { value: def });
- inst.parse = (data, params) => parse3(inst, data, params, { callee: inst.parse });
- inst.safeParse = (data, params) => safeParse2(inst, data, params);
- inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
- inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
- inst.spa = inst.safeParseAsync;
- inst.encode = (data, params) => encode(inst, data, params);
- inst.decode = (data, params) => decode(inst, data, params);
- inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
- inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
- inst.safeEncode = (data, params) => safeEncode(inst, data, params);
- inst.safeDecode = (data, params) => safeDecode(inst, data, params);
- inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
- inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
- _installLazyMethods(inst, "ZodType", {
- check(...chks) {
- const def = this.def;
- return this.clone(mergeDefs(def, {
- checks: [
- ...def.checks ?? [],
- ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
- ]
- }), { parent: true });
- },
- with(...chks) {
- return this.check(...chks);
- },
- clone(def, params) {
- return clone(this, def, params);
- },
- brand() {
- return this;
- },
- register(reg, meta) {
- reg.add(this, meta);
- return this;
- },
- refine(check, params) {
- return this.check(refine(check, params));
- },
- superRefine(refinement, params) {
- return this.check(superRefine(refinement, params));
- },
- overwrite(fn) {
- return this.check(_overwrite(fn));
- },
- optional() {
- return optional(this);
- },
- exactOptional() {
- return exactOptional(this);
- },
- nullable() {
- return nullable(this);
- },
- nullish() {
- return optional(nullable(this));
- },
- nonoptional(params) {
- return nonoptional(this, params);
- },
- array() {
- return array(this);
- },
- or(arg) {
- return union([this, arg]);
- },
- and(arg) {
- return intersection(this, arg);
- },
- transform(tx) {
- return pipe(this, transform(tx));
- },
- default(d) {
- return _default(this, d);
- },
- prefault(d) {
- return prefault(this, d);
- },
- catch(params) {
- return _catch(this, params);
- },
- pipe(target) {
- return pipe(this, target);
- },
- readonly() {
- return readonly(this);
- },
- describe(description) {
- const cl = this.clone();
- globalRegistry.add(cl, { description });
- return cl;
- },
- meta(...args) {
- if (args.length === 0)
- return globalRegistry.get(this);
- const cl = this.clone();
- globalRegistry.add(cl, args[0]);
- return cl;
- },
- isOptional() {
- return this.safeParse(undefined).success;
- },
- isNullable() {
- return this.safeParse(null).success;
- },
- apply(fn) {
- return fn(this);
- }
- });
- Object.defineProperty(inst, "description", {
- get() {
- return globalRegistry.get(inst)?.description;
- },
- configurable: true
- });
return inst;
+}, {
+ check(...chks) {
+ const def = this.def;
+ return this.clone(mergeDefs(def, {
+ checks: [
+ ...def.checks ?? [],
+ ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
+ ]
+ }), { parent: true });
+ },
+ with(...chks) {
+ return this.check(...chks);
+ },
+ clone(def, params) {
+ return clone(this, def, params);
+ },
+ brand() {
+ return this;
+ },
+ register(reg, meta) {
+ reg.add(this, meta);
+ return this;
+ },
+ refine(check, params) {
+ return this.check(refine(check, params));
+ },
+ superRefine(refinement, params) {
+ return this.check(superRefine(refinement, params));
+ },
+ overwrite(fn) {
+ return this.check(_overwrite(fn));
+ },
+ optional() {
+ return optional(this);
+ },
+ exactOptional() {
+ return exactOptional(this);
+ },
+ nullable() {
+ return nullable(this);
+ },
+ nullish() {
+ return optional(nullable(this));
+ },
+ nonoptional(params) {
+ return nonoptional(this, params);
+ },
+ array() {
+ return array(this);
+ },
+ or(arg) {
+ return union([this, arg]);
+ },
+ and(arg) {
+ return intersection(this, arg);
+ },
+ transform(tx) {
+ return pipe(this, transform(tx));
+ },
+ default(d) {
+ return _default(this, d);
+ },
+ prefault(d) {
+ return prefault(this, d);
+ },
+ catch(params) {
+ return _catch(this, params);
+ },
+ pipe(target) {
+ return pipe(this, target);
+ },
+ readonly() {
+ return readonly(this);
+ },
+ describe(description) {
+ const cl = this.clone();
+ globalRegistry.add(cl, { description });
+ return cl;
+ },
+ meta(...args) {
+ if (args.length === 0)
+ return globalRegistry.get(this);
+ const cl = this.clone();
+ globalRegistry.add(cl, args[0]);
+ return cl;
+ },
+ isOptional() {
+ return this.safeParse(undefined).success;
+ },
+ isNullable() {
+ return this.safeParse(null).success;
+ },
+ apply(fn, ...args) {
+ return args.length === 0 ? fn(this) : fn(this, ...args);
+ },
+ get "~standard"() {
+ return hide(this, "~standard", {
+ ...standardProps(this),
+ jsonSchema: {
+ input: createStandardJSONSchemaMethod(this, "input"),
+ output: createStandardJSONSchemaMethod(this, "output")
+ }
+ });
+ },
+ set "~standard"(value) {
+ own(this, "~standard", value);
+ },
+ parse: function _parse(data, params) {
+ return parse2(this, data, params, { callee: _parse });
+ },
+ parseAsync: async function _parseAsync(data, params) {
+ return await parseAsync(this, data, params, { callee: _parseAsync });
+ },
+ safeParse(data, params) {
+ return safeParse(this, data, params);
+ },
+ async safeParseAsync(data, params) {
+ return safeParseAsync(this, data, params);
+ },
+ get spa() {
+ return this?.safeParseAsync;
+ },
+ set spa(value) {
+ own(this, "spa", value);
+ },
+ validate(data, params) {
+ return validate(this, data, params);
+ },
+ validateAsync(data, params) {
+ return validateAsync(this, data, params);
+ },
+ encode: function _encode(data, params) {
+ return encode(this, data, params, { callee: _encode });
+ },
+ decode: function _decode(data, params) {
+ return decode(this, data, params, { callee: _decode });
+ },
+ encodeAsync: async function _encodeAsync(data, params) {
+ return await encodeAsync(this, data, params, { callee: _encodeAsync });
+ },
+ decodeAsync: async function _decodeAsync(data, params) {
+ return await decodeAsync(this, data, params, { callee: _decodeAsync });
+ },
+ safeEncode(data, params) {
+ return safeEncode(this, data, params);
+ },
+ safeDecode(data, params) {
+ return safeDecode(this, data, params);
+ },
+ async safeEncodeAsync(data, params) {
+ return safeEncodeAsync(this, data, params);
+ },
+ async safeDecodeAsync(data, params) {
+ return safeDecodeAsync(this, data, params);
+ },
+ toJSONSchema(params) {
+ return createToJSONSchemaMethod(this, {})(params);
+ },
+ get description() {
+ return globalRegistry.get(this)?.description;
+ },
+ get _def() {
+ return this._zod.def;
+ }
});
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
- const bag = inst._zod.bag;
- inst.format = bag.format ?? null;
- inst.minLength = bag.minimum ?? null;
- inst.maxLength = bag.maximum ?? null;
- _installLazyMethods(inst, "_ZodString", {
- regex(...args) {
- return this.check(_regex(...args));
- },
- includes(...args) {
- return this.check(_includes(...args));
- },
- startsWith(...args) {
- return this.check(_startsWith(...args));
- },
- endsWith(...args) {
- return this.check(_endsWith(...args));
- },
- min(...args) {
- return this.check(_minLength(...args));
- },
- max(...args) {
- return this.check(_maxLength(...args));
- },
- length(...args) {
- return this.check(_length(...args));
- },
- nonempty(...args) {
- return this.check(_minLength(1, ...args));
- },
- lowercase(params) {
- return this.check(_lowercase(params));
- },
- uppercase(params) {
- return this.check(_uppercase(params));
- },
- trim() {
- return this.check(_trim());
- },
- normalize(...args) {
- return this.check(_normalize(...args));
- },
- toLowerCase() {
- return this.check(_toLowerCase());
- },
- toUpperCase() {
- return this.check(_toUpperCase());
- },
- slugify() {
- return this.check(_slugify());
- }
- });
-});
+}, /* @__PURE__ */ derived({
+ format: (inst) => aggregateChecks(inst).format ?? null,
+ minLength: (inst) => aggregateChecks(inst).minimum ?? null,
+ maxLength: (inst) => aggregateChecks(inst).maximum ?? null
+}, {
+ regex(...args) {
+ return this.check(_regex(...args));
+ },
+ includes(...args) {
+ return this.check(_includes(...args));
+ },
+ startsWith(...args) {
+ return this.check(_startsWith(...args));
+ },
+ endsWith(...args) {
+ return this.check(_endsWith(...args));
+ },
+ min(...args) {
+ return this.check(_minLength(...args));
+ },
+ max(...args) {
+ return this.check(_maxLength(...args));
+ },
+ length(...args) {
+ return this.check(_length(...args));
+ },
+ nonempty(...args) {
+ return this.check(_minLength(1, ...args));
+ },
+ lowercase(params) {
+ return this.check(_lowercase(params));
+ },
+ uppercase(params) {
+ return this.check(_uppercase(params));
+ },
+ trim() {
+ return this.check(_trim());
+ },
+ normalize(...args) {
+ return this.check(_normalize(...args));
+ },
+ toLowerCase() {
+ return this.check(_toLowerCase());
+ },
+ toUpperCase() {
+ return this.check(_toUpperCase());
+ },
+ slugify() {
+ return this.check(_slugify());
+ }
+}));
var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
$ZodString.init(inst, def);
_ZodString.init(inst, def);
- inst.email = (params) => inst.check(_email(ZodEmail, params));
- inst.url = (params) => inst.check(_url(ZodURL, params));
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
- inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
- inst.datetime = (params) => inst.check(datetime2(params));
- inst.date = (params) => inst.check(date2(params));
- inst.time = (params) => inst.check(time2(params));
- inst.duration = (params) => inst.check(duration2(params));
+}, {
+ email(params) {
+ return this.check(_email(ZodEmail, params));
+ },
+ url(params) {
+ return this.check(_url(ZodURL, params));
+ },
+ jwt(params) {
+ return this.check(_jwt(ZodJWT, params));
+ },
+ emoji(params) {
+ return this.check(_emoji2(ZodEmoji, params));
+ },
+ guid(params) {
+ return this.check(_guid(ZodGUID, params));
+ },
+ uuid(params) {
+ return this.check(_uuid(ZodUUID, params));
+ },
+ uuidv4(params) {
+ return this.check(_uuidv4(ZodUUID, params));
+ },
+ uuidv6(params) {
+ return this.check(_uuidv6(ZodUUID, params));
+ },
+ uuidv7(params) {
+ return this.check(_uuidv7(ZodUUID, params));
+ },
+ nanoid(params) {
+ return this.check(_nanoid(ZodNanoID, params));
+ },
+ cuid(params) {
+ return this.check(_cuid(ZodCUID, params));
+ },
+ cuid2(params) {
+ return this.check(_cuid2(ZodCUID2, params));
+ },
+ ulid(params) {
+ return this.check(_ulid(ZodULID, params));
+ },
+ base64(params) {
+ return this.check(_base64(ZodBase64, params));
+ },
+ base64url(params) {
+ return this.check(_base64url(ZodBase64URL, params));
+ },
+ xid(params) {
+ return this.check(_xid(ZodXID, params));
+ },
+ ksuid(params) {
+ return this.check(_ksuid(ZodKSUID, params));
+ },
+ ipv4(params) {
+ return this.check(_ipv4(ZodIPv4, params));
+ },
+ ipv6(params) {
+ return this.check(_ipv6(ZodIPv6, params));
+ },
+ cidrv4(params) {
+ return this.check(_cidrv4(ZodCIDRv4, params));
+ },
+ cidrv6(params) {
+ return this.check(_cidrv6(ZodCIDRv6, params));
+ },
+ e164(params) {
+ return this.check(_e164(ZodE164, params));
+ },
+ datetime(params) {
+ return this.check(_isoDateTime(ZodISODateTime, params));
+ },
+ date(params) {
+ return this.check(_isoDate(ZodISODate, params));
+ },
+ time(params) {
+ return this.check(_isoTime(ZodISOTime, params));
+ },
+ duration(params) {
+ return this.check(_isoDuration(ZodISODuration, params));
+ }
});
function string2(params) {
return _string(ZodString, params);
@@ -5081,6 +6282,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
+var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
+ $ZodISODateTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
+ $ZodISODate.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
+ $ZodISOTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
+ $ZodISODuration.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
@@ -5161,60 +6378,68 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
$ZodNumber.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
- _installLazyMethods(inst, "ZodNumber", {
- gt(value, params) {
- return this.check(_gt(value, params));
- },
- gte(value, params) {
- return this.check(_gte(value, params));
- },
- min(value, params) {
- return this.check(_gte(value, params));
- },
- lt(value, params) {
- return this.check(_lt(value, params));
- },
- lte(value, params) {
- return this.check(_lte(value, params));
- },
- max(value, params) {
- return this.check(_lte(value, params));
- },
- int(params) {
- return this.check(int(params));
- },
- safe(params) {
- return this.check(int(params));
- },
- positive(params) {
- return this.check(_gt(0, params));
- },
- nonnegative(params) {
- return this.check(_gte(0, params));
- },
- negative(params) {
- return this.check(_lt(0, params));
- },
- nonpositive(params) {
- return this.check(_lte(0, params));
- },
- multipleOf(value, params) {
- return this.check(_multipleOf(value, params));
- },
- step(value, params) {
- return this.check(_multipleOf(value, params));
- },
- finite() {
- return this;
- }
- });
- const bag = inst._zod.bag;
- inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
- inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
- inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
inst.isFinite = true;
- inst.format = bag.format ?? null;
-});
+}, /* @__PURE__ */ derived({
+ minValue: (inst) => {
+ const { minimum, exclusiveMinimum } = aggregateChecks(inst);
+ return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);
+ },
+ maxValue: (inst) => {
+ const { maximum, exclusiveMaximum } = aggregateChecks(inst);
+ return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);
+ },
+ isInt: (inst) => {
+ const { isInt, multipleOf } = aggregateChecks(inst);
+ return !!isInt || !!multipleOf?.some(Number.isSafeInteger);
+ },
+ format: (inst) => aggregateChecks(inst).format ?? null
+}, {
+ gt(value, params) {
+ return this.check(_gt(value, params));
+ },
+ gte(value, params) {
+ return this.check(_gte(value, params));
+ },
+ min(value, params) {
+ return this.check(_gte(value, params));
+ },
+ lt(value, params) {
+ return this.check(_lt(value, params));
+ },
+ lte(value, params) {
+ return this.check(_lte(value, params));
+ },
+ max(value, params) {
+ return this.check(_lte(value, params));
+ },
+ int(params) {
+ return this.check(int(params));
+ },
+ safe(params) {
+ return this.check(int(params));
+ },
+ positive(params) {
+ return this.check(_gt(0, params));
+ },
+ nonnegative(params) {
+ return this.check(_gte(0, params));
+ },
+ negative(params) {
+ return this.check(_lt(0, params));
+ },
+ nonpositive(params) {
+ return this.check(_lte(0, params));
+ },
+ multipleOf(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ step(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ finite() {
+ return this;
+ }
+}));
function number2(params) {
return _number(ZodNumber, params);
}
@@ -5250,79 +6475,80 @@ function never(params) {
return _never(ZodNever, params);
}
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodArray.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
- _installLazyMethods(inst, "ZodArray", {
- min(n, params) {
- return this.check(_minLength(n, params));
- },
- nonempty(params) {
- return this.check(_minLength(1, params));
- },
- max(n, params) {
- return this.check(_maxLength(n, params));
- },
- length(n, params) {
- return this.check(_length(n, params));
- },
- unwrap() {
- return this.element;
- }
- });
+}, {
+ min(n, params) {
+ return this.check(_minLength(n, params));
+ },
+ nonempty(params) {
+ return this.check(_minLength(1, params));
+ },
+ max(n, params) {
+ return this.check(_maxLength(n, params));
+ },
+ length(n, params) {
+ return this.check(_length(n, params));
+ },
+ unwrap() {
+ return this.element;
+ }
});
function array(element, params) {
return _array(ZodArray, element, params);
}
var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodObjectJIT.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
- defineLazy(inst, "shape", () => {
- return def.shape;
- });
- _installLazyMethods(inst, "ZodObject", {
- keyof() {
- return _enum(Object.keys(this._zod.def.shape));
- },
- catchall(catchall) {
- return this.clone({ ...this._zod.def, catchall });
- },
- passthrough() {
- return this.clone({ ...this._zod.def, catchall: unknown() });
- },
- loose() {
- return this.clone({ ...this._zod.def, catchall: unknown() });
- },
- strict() {
- return this.clone({ ...this._zod.def, catchall: never() });
- },
- strip() {
- return this.clone({ ...this._zod.def, catchall: undefined });
- },
- extend(incoming) {
- return extend(this, incoming);
- },
- safeExtend(incoming) {
- return safeExtend(this, incoming);
- },
- merge(other) {
- return merge(this, other);
- },
- pick(mask) {
- return pick(this, mask);
- },
- omit(mask) {
- return omit(this, mask);
- },
- partial(...args) {
- return partial(ZodOptional, this, args[0]);
- },
- required(...args) {
- return required(ZodNonOptional, this, args[0]);
- }
- });
+ installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
+}, {
+ keyof() {
+ return _enum(Object.keys(this._zod.def.shape));
+ },
+ catchall(catchall) {
+ return this.clone(mergeDefs(this._zod.def, { catchall }));
+ },
+ passthrough() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
+ },
+ loose() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
+ },
+ strict() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: never() }));
+ },
+ strip() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: undefined }));
+ },
+ extend(incoming) {
+ return extend(this, incoming);
+ },
+ safeExtend(incoming) {
+ return safeExtend(this, incoming);
+ },
+ merge(other) {
+ return merge(this, other);
+ },
+ pick(mask) {
+ return pick(this, mask);
+ },
+ omit(mask) {
+ return omit(this, mask);
+ },
+ partial(...args) {
+ return partial(ZodOptional, this, args[0]);
+ },
+ exactPartial(...args) {
+ return partial(ZodExactOptional, this, args[0], "exactPartial");
+ },
+ required(...args) {
+ return required(ZodNonOptional, this, args[0]);
+ }
});
function object(shape, params) {
const def = {
@@ -5370,6 +6596,7 @@ function intersection(left, right) {
});
}
var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodRecord.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
@@ -5397,7 +6624,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
inst.enum = def.entries;
- inst.options = Object.values(def.entries);
+ inst.options = [...inst._zod.values];
const keys = new Set(Object.keys(def.entries));
inst.extract = (values, params) => {
const newEntries = {};
@@ -5460,6 +6687,7 @@ function literal(value, params) {
});
}
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodTransform.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
@@ -5475,7 +6703,8 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
if (_issue.fatal)
_issue.continue = false;
_issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
+ if (!("input" in _issue))
+ _issue.input = payload.value;
_issue.inst ?? (_issue.inst = inst);
payload.issues.push(issue(_issue));
}
@@ -5484,12 +6713,10 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
if (output instanceof Promise) {
return output.then((output) => {
payload.value = output;
- payload.fallback = true;
return payload;
});
}
payload.value = output;
- payload.fallback = true;
return payload;
};
});
@@ -5590,7 +6817,7 @@ function _catch(innerType, catchValue) {
return new ZodCatch({
type: "catch",
innerType,
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
+ catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
});
}
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
@@ -6836,7 +8063,7 @@ var ParseOptions;
allowTrailingComma: false
};
})(ParseOptions || (ParseOptions = {}));
-function parse4(text, errors = [], options = ParseOptions.DEFAULT) {
+function parse3(text, errors = [], options = ParseOptions.DEFAULT) {
let currentProperty = null;
let currentParent = [];
const previousParents = [];
@@ -7163,7 +8390,7 @@ var SyntaxKind;
SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown";
SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
-var parse5 = parse4;
+var parse4 = parse3;
var ParseErrorCode;
(function(ParseErrorCode) {
ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol";
@@ -7414,7 +8641,7 @@ function resolveOmoConfigView(options) {
// ../../omo-config-core/src/loader/loader.ts
function parseJsoncSafe(content) {
const errors = [];
- const data = parse5(content.charCodeAt(0) === 65279 ? content.slice(1) : content, errors, {
+ const data = parse4(content.charCodeAt(0) === 65279 ? content.slice(1) : content, errors, {
allowTrailingComma: true,
disallowComments: false
});
diff --git a/plugins/omo/components/bootstrap/hooks/hooks.json b/plugins/omo/components/bootstrap/hooks/hooks.json
index 5a161258..ea141c3e 100644
--- a/plugins/omo/components/bootstrap/hooks/hooks.json
+++ b/plugins/omo/components/bootstrap/hooks/hooks.json
@@ -8,7 +8,7 @@
"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"",
"timeout": 30,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Bootstrap Provisioning"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Bootstrap Provisioning"
}
]
}
diff --git a/plugins/omo/components/bootstrap/package.json b/plugins/omo/components/bootstrap/package.json
index e883921f..96c5d7c1 100644
--- a/plugins/omo/components/bootstrap/package.json
+++ b/plugins/omo/components/bootstrap/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-bootstrap",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex SessionStart bootstrap component that provisions LazyCodex runtime dependencies from a detached worker.",
"type": "module",
"private": true,
diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.json
index d618a693..b7c03781 100644
--- a/plugins/omo/components/comment-checker/hooks/hooks.json
+++ b/plugins/omo/components/comment-checker/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 30,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Comments"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Comments"
}
]
}
diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.json
index ee121584..11056807 100644
--- a/plugins/omo/components/comment-checker/package.json
+++ b/plugins/omo/components/comment-checker/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-comment-checker",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.",
"type": "module",
"packageManager": "[email protected]",
@@ -46,11 +46,12 @@
"@code-yeongyu/comment-checker": "^0.8.0"
},
"devDependencies": {
+ "@vitest/coverage-v8": "5.0.1",
"@oh-my-opencode/comment-checker-core": "file:../../../../comment-checker-core",
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.json
index a69aa1d5..4f2edd7a 100644
--- a/plugins/omo/components/git-bash/hooks/hooks.json
+++ b/plugins/omo/components/git-bash/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Recommending Git Bash MCP"
+ "statusMessage": "(OmO 5.0.0-beta.81) Recommending Git Bash MCP"
}
]
}
@@ -20,7 +20,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Resetting Git Bash MCP Reminder"
+ "statusMessage": "(OmO 5.0.0-beta.81) Resetting Git Bash MCP Reminder"
}
]
}
diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.json
index dd285e14..5c44d205 100644
--- a/plugins/omo/components/git-bash/package.json
+++ b/plugins/omo/components/git-bash/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-git-bash-hook",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex hook component that reminds Windows sessions to prefer the OMO git_bash MCP.",
"type": "module",
"private": true,
@@ -17,7 +17,7 @@
"typecheck": "tsc --noEmit"
},
"devDependencies": {
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2"
},
"engines": {
diff --git a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json
index f93049e8..37288060 100644
--- a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json
+++ b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Verifying LazyCodex Executor Evidence"
+ "statusMessage": "(OmO 5.0.0-beta.81) Verifying LazyCodex Executor Evidence"
}
]
}
diff --git a/plugins/omo/components/lazycodex-executor-verify/package.json b/plugins/omo/components/lazycodex-executor-verify/package.json
index f9bcfd14..ec086c37 100644
--- a/plugins/omo/components/lazycodex-executor-verify/package.json
+++ b/plugins/omo/components/lazycodex-executor-verify/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-lazycodex-executor-verify",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex SubagentStop evidence verifier for LazyCodex executor completions.",
"type": "module",
"packageManager": "[email protected]",
@@ -33,10 +33,11 @@
"NOTICE"
],
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@vitest/coverage-v8": "5.0.1",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/lsp-daemon/dist/cli.js b/plugins/omo/components/lsp-daemon/dist/cli.js
index 8492d1cb..448fc814 100644
--- a/plugins/omo/components/lsp-daemon/dist/cli.js
+++ b/plugins/omo/components/lsp-daemon/dist/cli.js
@@ -3,14 +3,450 @@
// src/cli.ts
import { argv, stderr } from "node:process";
-// src/proxy.ts
-import { existsSync as existsSync13, realpathSync as realpathSync6 } from "node:fs";
-import { basename as basename4, delimiter as delimiter4, dirname as dirname11, isAbsolute as isAbsolute6 } from "node:path";
+// src/ownership.ts
+import { randomUUID } from "node:crypto";
+import { existsSync, lstatSync as lstatSync2, readFileSync as readFileSync3, statSync, unlinkSync as unlinkSync3 } from "node:fs";
+import { dirname as dirname3 } from "node:path";
+
+// src/lock.ts
+import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
+import { dirname } from "node:path";
+function isProcessAlive(pid) {
+ if (!Number.isInteger(pid) || pid <= 0)
+ return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ if (error instanceof Error)
+ return errorCode(error) === "EPERM";
+ throw error;
+ }
+}
+function readLockPid(lockPath) {
+ try {
+ const pid = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
+ return Number.isInteger(pid) ? pid : null;
+ } catch {
+ return null;
+ }
+}
+function tryAcquireLock(lockPath, ownerPid = process.pid) {
+ mkdirSync(dirname(lockPath), { recursive: true });
+ for (let attempt = 0;attempt < 2; attempt += 1) {
+ const handle = writeLockFile(lockPath, ownerPid);
+ if (handle)
+ return handle;
+ if (!reapStaleLock(lockPath))
+ return null;
+ }
+ return null;
+}
+function writeLockFile(lockPath, ownerPid) {
+ try {
+ const fd = openSync(lockPath, "wx", 384);
+ writeSync(fd, `${ownerPid}
+`);
+ closeSync(fd);
+ return { release: () => unlinkQuietly(lockPath) };
+ } catch (error) {
+ if (errorCode(error) === "EEXIST")
+ return null;
+ throw error;
+ }
+}
+function reapStaleLock(lockPath) {
+ const pid = readLockPid(lockPath);
+ if (pid !== null && isProcessAlive(pid))
+ return false;
+ unlinkQuietly(lockPath);
+ return true;
+}
+function unlinkQuietly(path) {
+ try {
+ unlinkSync(path);
+ } catch (error) {
+ if (error instanceof Error)
+ return;
+ throw error;
+ }
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+
+// src/ipc-protocol.ts
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import {
+ chmodSync,
+ closeSync as closeSync2,
+ constants,
+ fchmodSync,
+ fstatSync,
+ lstatSync,
+ mkdirSync as mkdirSync2,
+ openSync as openSync2,
+ readFileSync as readFileSync2,
+ unlinkSync as unlinkSync2,
+ writeSync as writeSync2
+} from "node:fs";
+import { dirname as dirname2 } from "node:path";
// ../mcp-stdio-core/src/record.ts
function isPlainRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+
+// src/ipc-protocol.ts
+var OMO_DAEMON_PROTOCOL_VERSION = 1;
+var AUTH_ERROR_CODE = -32001;
+var PROTOCOL_ERROR_CODE = -32002;
+var AUTH_TOKEN_BYTES = 32;
+
+class UnsafePrivateDirectoryError extends Error {
+ constructor(path, reason) {
+ super(`unsafe private directory ${path}: ${reason}`);
+ this.path = path;
+ this.reason = reason;
+ this.name = "UnsafePrivateDirectoryError";
+ this.code = "unsafe_private_directory";
+ }
+}
+function authEnvelope(token) {
+ return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
+}
+function readAuthToken(paths) {
+ try {
+ const token = readFileSync2(paths.auth, "utf8").trim();
+ return token.length > 0 ? token : null;
+ } catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+function readOrCreateAuthToken(paths) {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ return createAuthToken(paths);
+}
+function rotateAuthToken(paths) {
+ try {
+ unlinkSync2(paths.auth);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ }
+ return createAuthToken(paths);
+}
+function authenticateMessage(raw, expectedToken) {
+ const id = jsonRpcId(raw);
+ if (!isPlainRecord(raw))
+ return authError(id);
+ const params = raw["params"];
+ if (!isPlainRecord(params))
+ return authError(id);
+ const envelope = params["_omo"];
+ if (!isPlainRecord(envelope))
+ return authError(id);
+ const protocolVersion = envelope["protocolVersion"];
+ if (protocolVersion !== OMO_DAEMON_PROTOCOL_VERSION)
+ return protocolError(id);
+ const token = envelope["token"];
+ if (typeof token !== "string" || !tokenMatches(token, expectedToken))
+ return authError(id);
+ const cleanParams = { ...params };
+ delete cleanParams["_omo"];
+ return { input: { ...raw, params: cleanParams }, id, method: typeof raw["method"] === "string" ? raw["method"] : undefined };
+}
+function isAuthErrorResponse(message) {
+ if (!isPlainRecord(message))
+ return false;
+ const error = message["error"];
+ if (!isPlainRecord(error))
+ return false;
+ const data = error["data"];
+ return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
+}
+function writePrivateFile(path, data) {
+ const fd = openSync2(path, "w", 384);
+ try {
+ writeSync2(fd, data);
+ } finally {
+ closeSync2(fd);
+ }
+ setPrivateFileMode(path);
+}
+function ensurePrivateDirectory(path, options = {}) {
+ try {
+ mkdirSync2(path, { recursive: true, mode: 448 });
+ } catch (error) {
+ if (errorCode2(error) !== "EEXIST")
+ throw error;
+ }
+ if (process.platform === "win32")
+ return;
+ const before = validatePrivateDirectory(path, options);
+ const fd = openSync2(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ try {
+ fchmodSync(fd, 448);
+ const after = validatePrivateDirectory(path, options);
+ const openStats = fstatSync(fd);
+ if (!sameDirectory(before, after) || !sameDirectory(before, openStats)) {
+ throw new UnsafePrivateDirectoryError(path, "changed_during_chmod");
+ }
+ } finally {
+ closeSync2(fd);
+ }
+}
+function setPrivateFileMode(path) {
+ if (process.platform !== "win32")
+ chmodSync(path, 384);
+}
+function createAuthToken(paths) {
+ ensurePrivateDirectory(dirname2(paths.auth));
+ const token = randomBytes(AUTH_TOKEN_BYTES).toString("base64url");
+ let fd;
+ try {
+ fd = openSync2(paths.auth, "wx", 384);
+ } catch (error) {
+ if (errorCode2(error) === "EEXIST") {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ }
+ throw error;
+ }
+ try {
+ writeSync2(fd, `${token}
+`);
+ } finally {
+ closeSync2(fd);
+ }
+ setPrivateFileMode(paths.auth);
+ return token;
+}
+function errorCode2(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+function validatePrivateDirectory(path, options) {
+ const stats = options.lstat ? options.lstat(path) : lstatPrivateDirectory(path);
+ if (stats.isSymbolicLink())
+ throw new UnsafePrivateDirectoryError(path, "symlink");
+ if (!stats.isDirectory())
+ throw new UnsafePrivateDirectoryError(path, "not_directory");
+ const currentUid = options.currentUid ? options.currentUid() : process.getuid?.();
+ if (currentUid !== undefined && stats.uid !== currentUid) {
+ throw new UnsafePrivateDirectoryError(path, "wrong_owner");
+ }
+ return stats;
+}
+function lstatPrivateDirectory(path) {
+ return lstatSync(path);
+}
+function sameDirectory(a, b) {
+ return a.dev === b.dev && a.ino === b.ino;
+}
+function tokenMatches(candidate, expected) {
+ const candidateBytes = Buffer.from(candidate);
+ const expectedBytes = Buffer.from(expected);
+ return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
+}
+function jsonRpcId(raw) {
+ if (!isPlainRecord(raw))
+ return null;
+ const id = raw["id"];
+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;
+}
+function authError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: AUTH_ERROR_CODE, message: "daemon authentication failed", data: { code: "daemon_authentication_failed" } }
+ };
+}
+function protocolError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: PROTOCOL_ERROR_CODE, message: "daemon protocol mismatch", data: { code: "daemon_protocol_mismatch" } }
+ };
+}
+
+// src/ownership.ts
+class DaemonAlreadyRunningError extends Error {
+ constructor() {
+ super(...arguments);
+ this.name = "DaemonAlreadyRunningError";
+ this.code = "daemon_already_running";
+ }
+}
+
+class DaemonStartupDeferredError extends Error {
+ constructor(reason) {
+ super(`LSP daemon startup deferred: ${reason}`);
+ this.reason = reason;
+ this.name = "DaemonStartupDeferredError";
+ this.code = "daemon_startup_deferred";
+ }
+}
+async function acquireStartupLease(paths, pingOwner) {
+ ensureDaemonDirectories(paths);
+ const lock = tryAcquireLock(paths.lock);
+ if (!lock) {
+ const token = readAuthToken(paths);
+ if (token && await pingOwner(token))
+ throw new DaemonAlreadyRunningError("LSP daemon already running");
+ throw new DaemonStartupDeferredError("startup_lock_busy");
+ }
+ try {
+ const token = await validateExistingOwner(paths, pingOwner);
+ return { lock, token, owner: newOwner(paths) };
+ } catch (error) {
+ lock.release();
+ throw error;
+ }
+}
+function ensureDaemonDirectories(paths) {
+ ensurePrivateDirectory(paths.dir);
+ if (process.platform !== "win32")
+ ensurePrivateDirectory(dirname3(paths.socket));
+}
+function readDaemonOwner(paths) {
+ try {
+ return parseOwner(JSON.parse(readFileSync3(paths.owner, "utf8")));
+ } catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+function writeDaemonOwner(paths, owner) {
+ writePrivateFile(paths.pid, `${owner.pid}
+`);
+ writePrivateFile(paths.endpoint, owner.endpoint.path);
+ writePrivateFile(paths.owner, `${JSON.stringify(owner)}
+`);
+}
+function removeDaemonMetadataForOwner(paths, owner) {
+ const current = readDaemonOwner(paths);
+ if (!current || !sameOwner(current, owner))
+ return;
+ unlinkQuietly(paths.socket);
+ unlinkQuietly(paths.pid);
+ unlinkQuietly(paths.endpoint);
+ unlinkQuietly(paths.owner);
+}
+function endpointIdentity(endpointPath) {
+ if (process.platform === "win32")
+ return { kind: "windows", path: endpointPath };
+ try {
+ const stats = statSync(endpointPath);
+ return { kind: "unix", path: endpointPath, dev: stats.dev, ino: stats.ino };
+ } catch (error) {
+ if (error instanceof Error)
+ return { kind: "missing", path: endpointPath };
+ throw error;
+ }
+}
+function sameEndpoint(a, b) {
+ if (a.kind !== b.kind || a.path !== b.path)
+ return false;
+ switch (a.kind) {
+ case "unix":
+ return b.kind === "unix" && a.dev === b.dev && a.ino === b.ino;
+ case "windows":
+ return true;
+ case "missing":
+ return true;
+ }
+}
+function sameOwner(a, b) {
+ return a.pid === b.pid && a.nonce === b.nonce && sameEndpoint(a.endpoint, b.endpoint);
+}
+async function validateExistingOwner(paths, pingOwner) {
+ let token = readOrCreateAuthToken(paths);
+ for (let attempt = 0;attempt < 2; attempt += 1) {
+ const owner = readDaemonOwner(paths);
+ if (!owner)
+ return token;
+ const ping = await pingOwner(token);
+ if (ping && owner.nonce === ping.nonce && sameEndpoint(owner.endpoint, ping.endpoint)) {
+ throw new DaemonAlreadyRunningError("LSP daemon already running");
+ }
+ if (ping)
+ continue;
+ if (isProcessAlive(owner.pid))
+ throw new DaemonStartupDeferredError("owner_pid_live_unreachable");
+ const reread = readDaemonOwner(paths);
+ if (!reread || !sameOwner(reread, owner)) {
+ throw new DaemonStartupDeferredError("owner_changed_during_cleanup");
+ }
+ cleanupDeadOwner(paths, owner);
+ token = rotateAuthToken(paths);
+ return token;
+ }
+ throw new DaemonStartupDeferredError("reachable_owner_mismatch");
+}
+function cleanupDeadOwner(paths, owner) {
+ if (process.platform !== "win32" && existsSync(owner.endpoint.path)) {
+ const stat = lstatSync2(owner.endpoint.path);
+ if (stat.isSocket())
+ unlinkSync3(owner.endpoint.path);
+ }
+ unlinkQuietly(paths.pid);
+ unlinkQuietly(paths.endpoint);
+ unlinkQuietly(paths.owner);
+}
+function newOwner(paths) {
+ return {
+ pid: process.pid,
+ nonce: randomUUID(),
+ startedAt: new Date().toISOString(),
+ endpoint: endpointIdentity(paths.socket)
+ };
+}
+function parseOwner(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return null;
+ const pid = Reflect.get(value, "pid");
+ const nonce = Reflect.get(value, "nonce");
+ const startedAt = Reflect.get(value, "startedAt");
+ const endpoint = parseEndpoint(Reflect.get(value, "endpoint"));
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string" || !endpoint)
+ return null;
+ return { pid, nonce, startedAt, endpoint };
+}
+function parseEndpoint(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return null;
+ const kind = Reflect.get(value, "kind");
+ const path = Reflect.get(value, "path");
+ if (typeof path !== "string")
+ return null;
+ if (kind === undefined)
+ return endpointIdentity(path);
+ if (kind === "windows")
+ return { kind, path };
+ if (kind === "missing")
+ return { kind, path };
+ const dev = Reflect.get(value, "dev");
+ const ino = Reflect.get(value, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number")
+ return { kind, path, dev, ino };
+ return null;
+}
+
+// src/proxy.ts
+import { existsSync as existsSync14, realpathSync as realpathSync6 } from "node:fs";
+import { basename as basename4, delimiter as delimiter4, dirname as dirname13, isAbsolute as isAbsolute6 } from "node:path";
// ../mcp-stdio-core/src/responses.ts
function successResponse(id, result) {
return { jsonrpc: "2.0", id, result };
@@ -18,7 +454,7 @@ function successResponse(id, result) {
function errorResponse(id, code, message, data) {
return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } };
}
-function jsonRpcId(value) {
+function jsonRpcId2(value) {
return typeof value === "string" || typeof value === "number" || value === null ? value : null;
}
function messageFromError(error) {
@@ -169,7 +605,7 @@ function bufferFromChunk(chunk) {
var DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;
var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;
var noopLog = () => {};
-function isProcessAlive(pid) {
+function isProcessAlive2(pid) {
try {
process.kill(pid, 0);
return true;
@@ -229,7 +665,7 @@ async function handleParseError(message, config, log) {
}
async function handleRequest(message, config, log) {
const parsed = message.payload;
- const id = isPlainRecord(parsed) ? jsonRpcId(parsed["id"]) : null;
+ const id = isPlainRecord(parsed) ? jsonRpcId2(parsed["id"]) : null;
const method = isPlainRecord(parsed) && typeof parsed["method"] === "string" ? parsed["method"] : null;
log("request", { id: id === null ? null : String(id), method });
let response;
@@ -278,7 +714,7 @@ function createParentWatchdog(config, onDeadParent) {
if (pollIntervalMs <= 0)
return { clear: () => {} };
const parentPid = config.parentPid ?? process.ppid;
- const probeAlive = config.probeAlive ?? isProcessAlive;
+ const probeAlive = config.probeAlive ?? isProcessAlive2;
let fired = false;
const timer = setInterval(() => {
if (fired)
@@ -320,14 +756,14 @@ function createIdleTimer(idleTimeoutMs, log, onTimeout) {
};
}
// ../lsp-core/src/lsp/client-wrapper.ts
-import { existsSync as existsSync10, realpathSync as realpathSync5, statSync as statSync3 } from "node:fs";
-import { basename as basename3, dirname as dirname8, join as join5, resolve as resolve8 } from "node:path";
+import { existsSync as existsSync11, realpathSync as realpathSync5, statSync as statSync4 } from "node:fs";
+import { basename as basename3, dirname as dirname11, join as join5, resolve as resolve8 } from "node:path";
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
-import { existsSync, realpathSync, statSync } from "node:fs";
+import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
import { homedir } from "node:os";
-import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+import { basename, delimiter, dirname as dirname4, isAbsolute, join, relative, resolve } from "node:path";
class LspRequestContextParseError extends Error {
constructor(code, message) {
@@ -413,7 +849,7 @@ function translateHomeConfigEnv(value, home, fallback) {
}
function canonicalCwd(cwd) {
const resolved = resolve(cwd);
- if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ if (!existsSync2(resolved) || !statSync2(resolved).isDirectory()) {
throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
}
return realpathSync(resolved);
@@ -428,7 +864,7 @@ function canonicalizeExistingOrNearestAncestor(path) {
} catch (error) {
if (!isMissingPathError(error))
throw error;
- const parent = dirname(current);
+ const parent = dirname4(current);
if (parent === current)
throw error;
suffix.unshift(basename(current));
@@ -472,7 +908,7 @@ function isPathInside(parent, child) {
return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
}
function isMissingPathError(error) {
- const code = errorCode(error);
+ const code = errorCode3(error);
return code === "ENOENT" || code === "ENOTDIR";
}
function rejectUnknownFields(value, allowed, scope) {
@@ -484,7 +920,7 @@ function rejectUnknownFields(value, allowed, scope) {
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-function errorCode(error) {
+function errorCode3(error) {
if (!error || typeof error !== "object" || !("code" in error))
return;
const code = Reflect.get(error, "code");
@@ -939,7 +1375,7 @@ function toError(error) {
// ../lsp-core/src/lsp/process.ts
import { spawn, spawnSync } from "node:child_process";
-import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
+import { existsSync as existsSync3, statSync as statSync3 } from "node:fs";
import { delimiter as delimiter2, join as join2 } from "node:path";
function isMissingProcessError(error) {
if (!(error instanceof Error) || !("code" in error))
@@ -953,10 +1389,10 @@ function reportKillError(context, error) {
}
function validateCwd(cwd) {
try {
- if (!existsSync2(cwd)) {
+ if (!existsSync3(cwd)) {
return { valid: false, error: `Working directory does not exist: ${cwd}` };
}
- const stats = statSync2(cwd);
+ const stats = statSync3(cwd);
if (!stats.isDirectory()) {
return { valid: false, error: `Path is not a directory: ${cwd}` };
}
@@ -1041,7 +1477,7 @@ function resolveWindowsCommand(command, env) {
for (const baseDirectory of baseDirectories) {
for (const extension of extensions) {
const candidate = baseDirectory ? join2(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
- if (existsSync2(candidate))
+ if (existsSync3(candidate))
return candidate;
}
}
@@ -1460,7 +1896,7 @@ class LspClientConnection extends LspClientTransport {
}
// ../lsp-core/src/lsp/workspace-document-state.ts
-import { readFileSync, realpathSync as realpathSync2 } from "node:fs";
+import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "node:fs";
import { relative as relative2, resolve as resolve2 } from "node:path";
import { pathToFileURL as pathToFileURL2 } from "node:url";
@@ -1689,7 +2125,7 @@ class WorkspaceDocumentState {
await existingOpen;
return this.openFile(path);
}
- const text = readFileSync(path, "utf-8");
+ const text = readFileSync4(path, "utf-8");
const existing = this.openDocuments.get(path);
if (!existing)
return this.openDocumentSingleFlight(path, text);
@@ -1848,7 +2284,7 @@ class WorkspaceDocumentState {
const state = this.openDocuments.get(mutation.path);
if (state) {
await this.closeDocument(state);
- await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ await this.openDocumentSingleFlight(mutation.path, readFileSync4(mutation.path, "utf-8"));
} else {
watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
}
@@ -1860,7 +2296,7 @@ class WorkspaceDocumentState {
await this.closeDocument(state);
for (const state of moved) {
const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
- await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ await this.openDocumentSingleFlight(path, readFileSync4(path, "utf-8"));
}
if (moved.length === 0) {
watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
@@ -1936,11 +2372,11 @@ function workspaceApplyEditConcurrentFailureReason(phase) {
}
// ../lsp-core/src/lsp/workspace-edit-commit.ts
-import { existsSync as existsSync4, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync as existsSync5, lstatSync as lstatSync4, renameSync, rmSync, writeFileSync } from "node:fs";
// ../lsp-core/src/lsp/workspace-edit-path.ts
-import { existsSync as existsSync3, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync3 } from "node:fs";
-import { dirname as dirname2, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve3 } from "node:path";
+import { existsSync as existsSync4, lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync, realpathSync as realpathSync3 } from "node:fs";
+import { dirname as dirname5, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve3 } from "node:path";
import { fileURLToPath } from "node:url";
class WorkspaceEditPathError extends Error {
@@ -1957,8 +2393,8 @@ function isPathInsideWorkspace(filePath, workspaceRoot) {
}
function canonicalizeMissingPath(filePath) {
let ancestor = filePath;
- while (!existsSync3(ancestor)) {
- const parent = dirname2(ancestor);
+ while (!existsSync4(ancestor)) {
+ const parent = dirname5(ancestor);
if (parent === ancestor)
throw new WorkspaceEditPathError(filePath, "no existing ancestor");
ancestor = parent;
@@ -1968,14 +2404,14 @@ function canonicalizeMissingPath(filePath) {
function canonicalWorkspaceRoot(workspaceRoot) {
try {
const canonical = realpathSync3(resolve3(workspaceRoot));
- if (!lstatSync(canonical).isDirectory()) {
+ if (!lstatSync3(canonical).isDirectory()) {
return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
}
return {
success: true,
path: canonical,
requestedPath: resolve3(workspaceRoot),
- followedSymbolicLink: existsSync3(resolve3(workspaceRoot)) && lstatSync(resolve3(workspaceRoot)).isSymbolicLink()
+ followedSymbolicLink: existsSync4(resolve3(workspaceRoot)) && lstatSync3(resolve3(workspaceRoot)).isSymbolicLink()
};
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
@@ -1995,7 +2431,7 @@ function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
return { success: false, error: `non-file URI ${uri}: ${detail}` };
}
try {
- const canonical = existsSync3(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
+ const canonical = existsSync4(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
}
@@ -2003,7 +2439,7 @@ function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
success: true,
path: canonical,
requestedPath,
- followedSymbolicLink: existsSync3(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ followedSymbolicLink: existsSync4(requestedPath) && lstatSync3(requestedPath).isSymbolicLink()
};
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
@@ -2011,11 +2447,11 @@ function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
}
}
function snapshotPath(path, includeChildren) {
- if (!existsSync3(path))
+ if (!existsSync4(path))
return { kind: "missing" };
- const stats = lstatSync(path);
+ const stats = lstatSync3(path);
if (stats.isFile())
- return { kind: "file", content: readFileSync2(path, "utf-8") };
+ return { kind: "file", content: readFileSync5(path, "utf-8") };
if (stats.isDirectory()) {
return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
}
@@ -2131,7 +2567,7 @@ function commitOperation(context, operation) {
}
if (operation.kind === "rename") {
if (operation.replaceDestination) {
- const targetKind = existsSync4(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ const targetKind = existsSync5(operation.newPath) && lstatSync4(operation.newPath).isDirectory() ? "directory" : "file";
io.remove(operation.newPath, targetKind === "directory");
accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
@@ -2495,7 +2931,7 @@ function parseDocumentChange(input) {
}
// ../lsp-core/src/lsp/workspace-edit-simulation.ts
-import { dirname as dirname3, relative as relative4, resolve as resolve4 } from "node:path";
+import { dirname as dirname6, relative as relative4, resolve as resolve4 } from "node:path";
// ../lsp-core/src/lsp/workspace-edit-text.ts
function comparePosition(left, right) {
@@ -2619,7 +3055,7 @@ function virtualDirectoryHasChildren(virtual, path) {
return false;
}
function requireVirtualParent(virtual, path, changeIndex) {
- if (virtual.get(dirname3(path))?.kind !== "directory") {
+ if (virtual.get(dirname6(path))?.kind !== "directory") {
throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
}
}
@@ -2739,8 +3175,8 @@ function simulateDelete(operation, virtual) {
}
// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
-import { existsSync as existsSync5, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
-import { dirname as dirname4, resolve as resolve5 } from "node:path";
+import { existsSync as existsSync6, lstatSync as lstatSync5, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname7, resolve as resolve5 } from "node:path";
class WorkspaceSnapshotBuilder {
constructor(workspaceRoot) {
this.workspaceRoot = workspaceRoot;
@@ -2774,9 +3210,9 @@ class WorkspaceSnapshotBuilder {
}
if (candidate === this.workspaceRoot)
break;
- candidate = dirname4(candidate);
+ candidate = dirname7(candidate);
}
- if (!includeChildren || !existsSync5(path) || !lstatSync3(path).isDirectory())
+ if (!includeChildren || !existsSync6(path) || !lstatSync5(path).isDirectory())
return;
for (const child of readdirSync2(path))
this.add(resolve5(path, child), true);
@@ -3641,8 +4077,8 @@ async function disposeDefaultLspManager() {
}
// ../lsp-core/src/lsp/outside-context-workspace.ts
-import { existsSync as existsSync6, realpathSync as realpathSync4 } from "node:fs";
-import { dirname as dirname5, join as join3 } from "node:path";
+import { existsSync as existsSync7, realpathSync as realpathSync4 } from "node:fs";
+import { dirname as dirname8, join as join3 } from "node:path";
// ../lsp-core/src/lsp/workspace-markers.ts
var GIT_WORKSPACE_MARKER = ".git";
@@ -3666,10 +4102,10 @@ function findWorkspaceRootOutsideContext(directory) {
function nearestMarkedAncestor(directory) {
let current = directory;
for (;; ) {
- if (existsSync6(current) && WORKSPACE_MARKERS.some((marker) => existsSync6(join3(current, marker)))) {
+ if (existsSync7(current) && WORKSPACE_MARKERS.some((marker) => existsSync7(join3(current, marker)))) {
return realpathSync4(current);
}
- const parent = dirname5(current);
+ const parent = dirname8(current);
if (parent === current)
return;
current = parent;
@@ -3677,8 +4113,8 @@ function nearestMarkedAncestor(directory) {
}
function nearestExistingAncestor(directory) {
let current = directory;
- while (!existsSync6(current)) {
- const parent = dirname5(current);
+ while (!existsSync7(current)) {
+ const parent = dirname8(current);
if (parent === current)
return current;
current = parent;
@@ -3854,17 +4290,17 @@ var BUILTIN_SERVERS = {
};
// ../lsp-core/src/lsp/server-install-state.ts
-import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname6 } from "node:path";
+import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname9 } from "node:path";
function getInstallDecisionsPath() {
return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
const path = getInstallDecisionsPath();
- if (!existsSync7(path))
+ if (!existsSync8(path))
return {};
try {
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -3883,7 +4319,7 @@ function isInstallDecision(value) {
}
function writeInstallDecisions(decisions) {
const path = getInstallDecisionsPath();
- mkdirSync(dirname6(path), { recursive: true });
+ mkdirSync3(dirname9(path), { recursive: true });
const tmpPath = `${path}.tmp`;
writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
@@ -3902,7 +4338,7 @@ function isRecord5(value) {
}
// ../lsp-core/src/lsp/config-loader.ts
-import { existsSync as existsSync8, readFileSync as readFileSync4 } from "node:fs";
+import { existsSync as existsSync9, readFileSync as readFileSync7 } from "node:fs";
function getProjectConfigPaths() {
return lspRequestContext().projectConfigPaths;
}
@@ -3910,10 +4346,10 @@ function getUserConfigPath() {
return lspRequestContext().userConfigPath;
}
function loadJsonFile(path) {
- if (!existsSync8(path))
+ if (!existsSync9(path))
return null;
try {
- const parsed = JSON.parse(readFileSync4(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync7(path, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -4098,8 +4534,8 @@ function getDisabledServerIds() {
}
// ../lsp-core/src/lsp/server-installation.ts
-import { existsSync as existsSync9 } from "node:fs";
-import { delimiter as delimiter3, dirname as dirname7, isAbsolute as isAbsolute3, join as join4, resolve as resolve7 } from "node:path";
+import { existsSync as existsSync10 } from "node:fs";
+import { delimiter as delimiter3, dirname as dirname10, isAbsolute as isAbsolute3, join as join4, resolve as resolve7 } from "node:path";
var LOCAL_BIN_RULES = [
{
markers: ["package.json", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"],
@@ -4139,7 +4575,7 @@ var resolutionCache = new Map;
var probeCount = 0;
function probe(path) {
probeCount += 1;
- return existsSync9(path);
+ return existsSync10(path);
}
function executableSuffixes(platform, pathExt) {
if (platform !== "win32")
@@ -4173,7 +4609,7 @@ function resolveLocal(command, workingDirectory, suffixes, stopAt) {
return null;
if (boundary !== undefined && current === boundary)
return null;
- const parent = dirname7(current);
+ const parent = dirname10(current);
if (parent === current)
return null;
current = parent;
@@ -4328,7 +4764,7 @@ function getAllServers() {
// ../lsp-core/src/lsp/client-wrapper.ts
function isDirectoryPath(filePath) {
try {
- return statSync3(filePath).isDirectory();
+ return statSync4(filePath).isDirectory();
} catch {
return false;
}
@@ -4338,7 +4774,7 @@ function findWorkspaceRoot(filePath) {
const abs = resolveReadablePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname8(dir);
+ dir = dirname11(dir);
}
if (!isPathInside(cwd, abs))
return findWorkspaceRootOutsideContext(dir);
@@ -4347,7 +4783,7 @@ function findWorkspaceRoot(filePath) {
while (isPathInside(cwd, dir)) {
const canonicalDir = existingDirectoryInsideContext(dir, cwd);
if (canonicalDir !== undefined) {
- if (existsSync10(join5(dir, GIT_WORKSPACE_MARKER))) {
+ if (existsSync11(join5(dir, GIT_WORKSPACE_MARKER))) {
return canonicalDir;
}
if (nearestPackageRoot === undefined && hasProjectWorkspaceMarker(dir)) {
@@ -4356,12 +4792,12 @@ function findWorkspaceRoot(filePath) {
}
if (dir === cwd)
break;
- dir = dirname8(dir);
+ dir = dirname11(dir);
}
return nearestPackageRoot ?? fallbackRoot;
}
function hasProjectWorkspaceMarker(directory) {
- return PROJECT_WORKSPACE_MARKERS.some((marker) => existsSync10(join5(directory, marker)));
+ return PROJECT_WORKSPACE_MARKERS.some((marker) => existsSync11(join5(directory, marker)));
}
function resolveReadablePathInsideContext(filePath) {
const cwd = contextCwd();
@@ -4386,12 +4822,12 @@ function rebaseThroughCanonicalAncestor(path, cwd) {
let current = path;
const suffix = [];
while (true) {
- if (existsSync10(current)) {
+ if (existsSync11(current)) {
const canonical = realpathSync5(current);
if (isPathInside(cwd, canonical))
return suffix.length === 0 ? canonical : join5(canonical, ...suffix);
}
- const parent = dirname8(current);
+ const parent = dirname11(current);
if (parent === current)
return;
suffix.unshift(basename3(current));
@@ -4399,10 +4835,10 @@ function rebaseThroughCanonicalAncestor(path, cwd) {
}
}
function existingDirectoryInsideContext(directory, cwd) {
- if (!existsSync10(directory))
+ if (!existsSync11(directory))
return;
const canonical = realpathSync5(directory);
- if (!statSync3(canonical).isDirectory())
+ if (!statSync4(canonical).isDirectory())
return;
return isPathInside(cwd, canonical) ? canonical : undefined;
}
@@ -4414,7 +4850,7 @@ function nearestExistingDirectoryInsideContext(directory, cwd) {
return canonical;
if (current === cwd)
return;
- current = dirname8(current);
+ current = dirname11(current);
}
return;
}
@@ -4544,7 +4980,7 @@ async function withLspClient(filePath, fn, toolName, options = {}) {
}
// ../lsp-core/src/lsp/directory-diagnostics.ts
-import { existsSync as existsSync11, lstatSync as lstatSync4, readdirSync as readdirSync3 } from "node:fs";
+import { existsSync as existsSync12, lstatSync as lstatSync6, readdirSync as readdirSync3 } from "node:fs";
import { join as join6, resolve as resolve9 } from "node:path";
// ../lsp-core/src/lsp/formatters.ts
@@ -4678,7 +5114,7 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
const fullPath = join6(currentDir, entry);
let stat;
try {
- stat = lstatSync4(fullPath);
+ stat = lstatSync6(fullPath);
} catch {
continue;
}
@@ -4701,7 +5137,7 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
const absDir = resolve9(options.workspaceRoot ?? contextCwd(), directory);
- if (!existsSync11(absDir)) {
+ if (!existsSync12(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
@@ -4787,7 +5223,7 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
}
// ../lsp-core/src/lsp/infer-extension.ts
-import { lstatSync as lstatSync5, readdirSync as readdirSync4 } from "node:fs";
+import { lstatSync as lstatSync7, readdirSync as readdirSync4 } from "node:fs";
import { join as join7 } from "node:path";
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
@@ -4809,7 +5245,7 @@ function inferExtensionFromDirectory(directory) {
const fullPath = join7(dir, entry);
let stat;
try {
- stat = lstatSync5(fullPath);
+ stat = lstatSync7(fullPath);
} catch {
continue;
}
@@ -5058,7 +5494,7 @@ async function executeLspDiagnostics(params, signal) {
}
}
// ../lsp-core/src/lsp/format-document.ts
-import { readFileSync as readFileSync5, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync3 } from "node:fs";
+import { readFileSync as readFileSync8, renameSync as renameSync3, unlinkSync as unlinkSync4, writeFileSync as writeFileSync3 } from "node:fs";
var DEFAULT_FORMATTING_OPTIONS = {
tabSize: 4,
insertSpaces: false,
@@ -5073,7 +5509,7 @@ async function formatDocumentWithClient(client, filePath, options = {}) {
return { status: "unavailable", reason: "capability_not_advertised" };
if (edits.length === 0)
return UNCHANGED;
- const before = readFileSync5(filePath, "utf-8");
+ const before = readFileSync8(filePath, "utf-8");
const normalized = normalizeTextEdits(before, edits, 0);
if (normalized.text === before)
return UNCHANGED;
@@ -5101,7 +5537,7 @@ function writeAtomically(filePath, content) {
renameSync3(tempPath, filePath);
} catch (error) {
try {
- unlinkSync(tempPath);
+ unlinkSync4(tempPath);
} catch {}
throw error;
}
@@ -5528,7 +5964,7 @@ async function handleLspMcpRequest(input, options = {}) {
if (!isPlainRecord(input)) {
return errorResponse(null, -32600, "Invalid Request");
}
- const id = jsonRpcId(input["id"]);
+ const id = jsonRpcId2(input["id"]);
const method = input["method"];
if (method === "notifications/initialized")
return;
@@ -5589,6 +6025,7 @@ function requestedProtocolVersion(params) {
import { connect } from "node:net";
import { homedir as homedir3 } from "node:os";
import { join as join8 } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
// src/daemon-request-error.ts
class DaemonRequestError extends Error {
@@ -5646,225 +6083,30 @@ function daemonTimedOutResult(paths, timeoutMs) {
`Logs: ${paths.log}`
].join(`
`);
- return { content: [{ type: "text", text }], isError: true };
-}
-function daemonUnreachableResult(paths, error) {
- const text = [
- `LSP daemon unreachable: ${errorText(error)}.`,
- "The MCP server is a thin proxy and never runs language servers in-process.",
- `Socket: ${paths.socket}`,
- `Logs: ${paths.log}`,
- "The daemon is auto-started on demand and will be retried on the next request."
- ].join(`
-`);
- return { content: [{ type: "text", text }], isError: true };
-}
-function errorText(error) {
- return error instanceof Error ? error.message : String(error);
-}
-
-// src/ensure-daemon.ts
-import { spawn as spawn2 } from "node:child_process";
-import { closeSync as closeSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, openSync as openSync2, writeSync as writeSync2 } from "node:fs";
-import { Socket } from "node:net";
-import { dirname as dirname10, isAbsolute as isAbsolute5 } from "node:path";
-import { argv0, execPath } from "node:process";
-
-// src/ipc-protocol.ts
-import { randomBytes, timingSafeEqual } from "node:crypto";
-import {
- chmodSync,
- closeSync,
- constants,
- fchmodSync,
- fstatSync,
- lstatSync as lstatSync6,
- mkdirSync as mkdirSync2,
- openSync,
- readFileSync as readFileSync6,
- unlinkSync as unlinkSync2,
- writeSync
-} from "node:fs";
-import { dirname as dirname9 } from "node:path";
-var OMO_DAEMON_PROTOCOL_VERSION = 1;
-var AUTH_ERROR_CODE = -32001;
-var PROTOCOL_ERROR_CODE = -32002;
-var AUTH_TOKEN_BYTES = 32;
-
-class UnsafePrivateDirectoryError extends Error {
- constructor(path, reason) {
- super(`unsafe private directory ${path}: ${reason}`);
- this.path = path;
- this.reason = reason;
- this.name = "UnsafePrivateDirectoryError";
- this.code = "unsafe_private_directory";
- }
-}
-function authEnvelope(token) {
- return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
-}
-function readAuthToken(paths) {
- try {
- const token = readFileSync6(paths.auth, "utf8").trim();
- return token.length > 0 ? token : null;
- } catch (error) {
- if (error instanceof Error)
- return null;
- throw error;
- }
-}
-function readOrCreateAuthToken(paths) {
- const existing = readAuthToken(paths);
- if (existing)
- return existing;
- return createAuthToken(paths);
-}
-function rotateAuthToken(paths) {
- try {
- unlinkSync2(paths.auth);
- } catch (error) {
- if (!(error instanceof Error))
- throw error;
- }
- return createAuthToken(paths);
-}
-function authenticateMessage(raw, expectedToken) {
- const id = jsonRpcId2(raw);
- if (!isPlainRecord(raw))
- return authError(id);
- const params = raw["params"];
- if (!isPlainRecord(params))
- return authError(id);
- const envelope = params["_omo"];
- if (!isPlainRecord(envelope))
- return authError(id);
- const protocolVersion = envelope["protocolVersion"];
- if (protocolVersion !== OMO_DAEMON_PROTOCOL_VERSION)
- return protocolError(id);
- const token = envelope["token"];
- if (typeof token !== "string" || !tokenMatches(token, expectedToken))
- return authError(id);
- const cleanParams = { ...params };
- delete cleanParams["_omo"];
- return { input: { ...raw, params: cleanParams }, id, method: typeof raw["method"] === "string" ? raw["method"] : undefined };
-}
-function isAuthErrorResponse(message) {
- if (!isPlainRecord(message))
- return false;
- const error = message["error"];
- if (!isPlainRecord(error))
- return false;
- const data = error["data"];
- return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
-}
-function writePrivateFile(path, data) {
- const fd = openSync(path, "w", 384);
- try {
- writeSync(fd, data);
- } finally {
- closeSync(fd);
- }
- setPrivateFileMode(path);
-}
-function ensurePrivateDirectory(path, options = {}) {
- try {
- mkdirSync2(path, { recursive: true, mode: 448 });
- } catch (error) {
- if (errorCode2(error) !== "EEXIST")
- throw error;
- }
- if (process.platform === "win32")
- return;
- const before = validatePrivateDirectory(path, options);
- const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
- try {
- fchmodSync(fd, 448);
- const after = validatePrivateDirectory(path, options);
- const openStats = fstatSync(fd);
- if (!sameDirectory(before, after) || !sameDirectory(before, openStats)) {
- throw new UnsafePrivateDirectoryError(path, "changed_during_chmod");
- }
- } finally {
- closeSync(fd);
- }
-}
-function setPrivateFileMode(path) {
- if (process.platform !== "win32")
- chmodSync(path, 384);
-}
-function createAuthToken(paths) {
- ensurePrivateDirectory(dirname9(paths.auth));
- const token = randomBytes(AUTH_TOKEN_BYTES).toString("base64url");
- let fd;
- try {
- fd = openSync(paths.auth, "wx", 384);
- } catch (error) {
- if (errorCode2(error) === "EEXIST") {
- const existing = readAuthToken(paths);
- if (existing)
- return existing;
- }
- throw error;
- }
- try {
- writeSync(fd, `${token}
-`);
- } finally {
- closeSync(fd);
- }
- setPrivateFileMode(paths.auth);
- return token;
-}
-function errorCode2(error) {
- if (!error || typeof error !== "object" || !("code" in error))
- return;
- const code = Reflect.get(error, "code");
- return typeof code === "string" ? code : undefined;
-}
-function validatePrivateDirectory(path, options) {
- const stats = options.lstat ? options.lstat(path) : lstatPrivateDirectory(path);
- if (stats.isSymbolicLink())
- throw new UnsafePrivateDirectoryError(path, "symlink");
- if (!stats.isDirectory())
- throw new UnsafePrivateDirectoryError(path, "not_directory");
- const currentUid = options.currentUid ? options.currentUid() : process.getuid?.();
- if (currentUid !== undefined && stats.uid !== currentUid) {
- throw new UnsafePrivateDirectoryError(path, "wrong_owner");
- }
- return stats;
-}
-function lstatPrivateDirectory(path) {
- return lstatSync6(path);
-}
-function sameDirectory(a, b) {
- return a.dev === b.dev && a.ino === b.ino;
-}
-function tokenMatches(candidate, expected) {
- const candidateBytes = Buffer.from(candidate);
- const expectedBytes = Buffer.from(expected);
- return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
-}
-function jsonRpcId2(raw) {
- if (!isPlainRecord(raw))
- return null;
- const id = raw["id"];
- return typeof id === "string" || typeof id === "number" || id === null ? id : null;
-}
-function authError(id) {
- return {
- jsonrpc: "2.0",
- id,
- error: { code: AUTH_ERROR_CODE, message: "daemon authentication failed", data: { code: "daemon_authentication_failed" } }
- };
+ return { content: [{ type: "text", text }], isError: true };
}
-function protocolError(id) {
- return {
- jsonrpc: "2.0",
- id,
- error: { code: PROTOCOL_ERROR_CODE, message: "daemon protocol mismatch", data: { code: "daemon_protocol_mismatch" } }
- };
+function daemonUnreachableResult(paths, error) {
+ const text = [
+ `LSP daemon unreachable: ${errorText(error)}.`,
+ "The MCP server is a thin proxy and never runs language servers in-process.",
+ `Socket: ${paths.socket}`,
+ `Logs: ${paths.log}`,
+ "The daemon is auto-started on demand and will be retried on the next request."
+ ].join(`
+`);
+ return { content: [{ type: "text", text }], isError: true };
+}
+function errorText(error) {
+ return error instanceof Error ? error.message : String(error);
}
+// src/ensure-daemon.ts
+import { spawn as spawn2 } from "node:child_process";
+import { closeSync as closeSync3, existsSync as existsSync13, mkdirSync as mkdirSync4, openSync as openSync3, writeSync as writeSync3 } from "node:fs";
+import { Socket } from "node:net";
+import { dirname as dirname12, isAbsolute as isAbsolute5 } from "node:path";
+import { argv0, execPath } from "node:process";
+
// src/paths.ts
import { createHash as createHash2 } from "node:crypto";
import { createRequire } from "node:module";
@@ -5873,7 +6115,7 @@ import * as path from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
// src/runtime-contract.ts
-import { statSync as statSync4 } from "node:fs";
+import { statSync as statSync5 } from "node:fs";
import { isAbsolute as isAbsolute4 } from "node:path";
var OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
@@ -5921,7 +6163,7 @@ function resolveDaemonRuntime(env, defaults) {
}
let cliStats;
try {
- cliStats = statSync4(cliOverride);
+ cliStats = statSync5(cliOverride);
} catch (error) {
if (!(error instanceof Error))
throw error;
@@ -6055,9 +6297,11 @@ function createLineDecoder(onMessage, onParseError) {
}
// src/ensure-daemon.ts
-var PROBE_TIMEOUT_MS = 500;
+var PROBE_TIMEOUT_MS = 2000;
var DEFAULT_READY_TIMEOUT_MS = 5000;
var DEFAULT_POLL_INTERVAL_MS = 100;
+var FAILED_SPAWN_COOLDOWN_MS = 5000;
+var failedSpawnUntil = new Map;
class DaemonUnreachableError extends Error {
constructor(socketPath) {
@@ -6070,11 +6314,22 @@ async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), opti
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const signal = options.signal;
throwIfAborted(signal);
- if (await awaitWithSignal2(deps.probe(paths, signal), signal))
+ if (await awaitWithSignal2(deps.probe(paths, signal), signal)) {
+ failedSpawnUntil.delete(paths.socket);
return;
+ }
throwIfAborted(signal);
+ const retryAt = failedSpawnUntil.get(paths.socket);
+ if (retryAt !== undefined && deps.now() < retryAt)
+ throw new DaemonUnreachableError(paths.socket);
+ failedSpawnUntil.delete(paths.socket);
deps.spawnDaemon(paths);
- await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ try {
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ } catch (error) {
+ failedSpawnUntil.set(paths.socket, deps.now() + FAILED_SPAWN_COOLDOWN_MS);
+ throw error;
+ }
}
async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal) {
const deadline = deps.now() + readyTimeoutMs;
@@ -6130,8 +6385,8 @@ function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS, signal) {
});
}
function spawnDaemonProcess(paths, deps = {}) {
- mkdirSync3(dirname10(paths.log), { recursive: true });
- const logFd = openSync2(paths.log, "a");
+ mkdirSync4(dirname12(paths.log), { recursive: true });
+ const logFd = openSync3(paths.log, "a");
try {
const spawnDaemonChild = deps.spawn ?? spawn2;
const executable = deps.resolveExecutable?.() ?? resolveDaemonNodeExecutable();
@@ -6141,19 +6396,19 @@ function spawnDaemonProcess(paths, deps = {}) {
windowsHide: true,
env: { ...process.env, BUN_BE_BUN: "1" }
});
- child.once("spawn", () => closeSync2(logFd));
+ child.once("spawn", () => closeSync3(logFd));
child.once("error", (error) => {
- writeSync2(logFd, `[lsp-daemon] failed to spawn daemon: ${error.message}
+ writeSync3(logFd, `[lsp-daemon] failed to spawn daemon: ${error.message}
`);
- closeSync2(logFd);
+ closeSync3(logFd);
});
child.unref();
} catch (error) {
- closeSync2(logFd);
+ closeSync3(logFd);
throw error;
}
}
-function resolveDaemonNodeExecutable(cachedExecPath = execPath, originalArgv0 = argv0, pathExists = existsSync12) {
+function resolveDaemonNodeExecutable(cachedExecPath = execPath, originalArgv0 = argv0, pathExists = existsSync13) {
if (pathExists(cachedExecPath))
return cachedExecPath;
if (isAbsolute5(originalArgv0) && pathExists(originalArgv0))
@@ -6337,6 +6592,7 @@ function parseContext(value) {
// src/daemon-client.ts
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
+var STARTUP_BACKOFF_MS = [0, 100, 300];
var nextProxyRequestId = 1;
async function callToolViaDaemon(name, args, options) {
const context = requireContext(options.context);
@@ -6344,17 +6600,31 @@ async function callToolViaDaemon(name, args, options) {
const ensure = options.ensure ?? ((ensurePaths, signal) => ensureDaemonRunning(ensurePaths, undefined, signal === undefined ? {} : { signal }));
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const requestArgs = withContext(args, context);
+ const probe = options.probe ?? ((probePaths, signal) => probeDaemon(probePaths, undefined, signal));
+ const sleep = options.sleep ?? ((ms, signal) => delay(ms, undefined, { signal }));
let lastError;
let authRefreshUsed = false;
- for (let attempt = 0;attempt < 3; attempt += 1) {
+ for (const [attempt, backoffMs] of STARTUP_BACKOFF_MS.entries()) {
try {
- await ensureDaemonAvailable(paths, ensure, options.signal);
+ if (backoffMs > 0)
+ await sleep(backoffMs, options.signal);
+ if (options.signal?.aborted)
+ throw new DaemonRequestCancelledError(false);
+ if (attempt === 0) {
+ await ensureDaemonAvailable(paths, ensure, options.signal);
+ } else if (!await probe(paths, options.signal)) {
+ throw new DaemonUnreachableError(paths.socket);
+ }
const token = readAuthToken(paths);
if (!token)
throw new DaemonRequestError("daemon auth token missing", false);
const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
+ if (options.signal?.aborted) {
+ lastError = new DaemonRequestCancelledError(false);
+ break;
+ }
lastError = error;
if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
authRefreshUsed = true;
@@ -6610,7 +6880,7 @@ function asToolCall(parsed) {
if (!isPlainRecord(params) || typeof params["name"] !== "string")
return null;
const args = params["arguments"];
- return { id: jsonRpcId(parsed["id"]), name: params["name"], args: isPlainRecord(args) ? args : {} };
+ return { id: jsonRpcId2(parsed["id"]), name: params["name"], args: isPlainRecord(args) ? args : {} };
}
function inferOpenCodeProjectCwd(projectConfigEnv) {
if (!projectConfigEnv)
@@ -6636,263 +6906,24 @@ function canonicalizePathList(value) {
return value.split(delimiter4).map((entry) => canonicalizePath(entry) ?? entry).join(delimiter4);
}
function canonicalizePath(value) {
- if (value === undefined || !isAbsolute6(value) || !existsSync13(value))
+ if (value === undefined || !isAbsolute6(value) || !existsSync14(value))
return value;
return realpathSync6(value);
}
function projectRootFromOpenCodeConfigPath(path) {
if (basename4(path) !== "lsp.json" && basename4(path) !== "lsp-client.json")
return;
- const configDir = dirname11(path);
+ const configDir = dirname13(path);
const configDirName = basename4(configDir);
if (configDirName !== ".opencode" && configDirName !== ".omo")
return;
- return dirname11(configDir);
+ return dirname13(configDir);
}
// src/daemon-server.ts
import { chmodSync as chmodSync2 } from "node:fs";
import { createServer as createServer2 } from "node:net";
-// src/ownership.ts
-import { randomUUID } from "node:crypto";
-import { existsSync as existsSync14, lstatSync as lstatSync7, readFileSync as readFileSync8, statSync as statSync5, unlinkSync as unlinkSync4 } from "node:fs";
-import { dirname as dirname13 } from "node:path";
-
-// src/lock.ts
-import { closeSync as closeSync3, mkdirSync as mkdirSync4, openSync as openSync3, readFileSync as readFileSync7, unlinkSync as unlinkSync3, writeSync as writeSync3 } from "node:fs";
-import { dirname as dirname12 } from "node:path";
-function isProcessAlive2(pid) {
- if (!Number.isInteger(pid) || pid <= 0)
- return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch (error) {
- if (error instanceof Error)
- return errorCode3(error) === "EPERM";
- throw error;
- }
-}
-function readLockPid(lockPath) {
- try {
- const pid = Number.parseInt(readFileSync7(lockPath, "utf8").trim(), 10);
- return Number.isInteger(pid) ? pid : null;
- } catch {
- return null;
- }
-}
-function tryAcquireLock(lockPath, ownerPid = process.pid) {
- mkdirSync4(dirname12(lockPath), { recursive: true });
- for (let attempt = 0;attempt < 2; attempt += 1) {
- const handle = writeLockFile(lockPath, ownerPid);
- if (handle)
- return handle;
- if (!reapStaleLock(lockPath))
- return null;
- }
- return null;
-}
-function writeLockFile(lockPath, ownerPid) {
- try {
- const fd = openSync3(lockPath, "wx", 384);
- writeSync3(fd, `${ownerPid}
-`);
- closeSync3(fd);
- return { release: () => unlinkQuietly(lockPath) };
- } catch (error) {
- if (errorCode3(error) === "EEXIST")
- return null;
- throw error;
- }
-}
-function reapStaleLock(lockPath) {
- const pid = readLockPid(lockPath);
- if (pid !== null && isProcessAlive2(pid))
- return false;
- unlinkQuietly(lockPath);
- return true;
-}
-function unlinkQuietly(path) {
- try {
- unlinkSync3(path);
- } catch (error) {
- if (error instanceof Error)
- return;
- throw error;
- }
-}
-function errorCode3(error) {
- if (!error || typeof error !== "object" || !("code" in error))
- return;
- const code = Reflect.get(error, "code");
- return typeof code === "string" ? code : undefined;
-}
-
-// src/ownership.ts
-class DaemonAlreadyRunningError extends Error {
- constructor() {
- super(...arguments);
- this.name = "DaemonAlreadyRunningError";
- this.code = "daemon_already_running";
- }
-}
-
-class DaemonStartupDeferredError extends Error {
- constructor(reason) {
- super(`LSP daemon startup deferred: ${reason}`);
- this.reason = reason;
- this.name = "DaemonStartupDeferredError";
- this.code = "daemon_startup_deferred";
- }
-}
-async function acquireStartupLease(paths, pingOwner) {
- ensureDaemonDirectories(paths);
- const lock = tryAcquireLock(paths.lock);
- if (!lock) {
- const token = readAuthToken(paths);
- if (token && await pingOwner(token))
- throw new DaemonAlreadyRunningError("LSP daemon already running");
- throw new DaemonStartupDeferredError("startup_lock_busy");
- }
- try {
- const token = await validateExistingOwner(paths, pingOwner);
- return { lock, token, owner: newOwner(paths) };
- } catch (error) {
- lock.release();
- throw error;
- }
-}
-function ensureDaemonDirectories(paths) {
- ensurePrivateDirectory(paths.dir);
- if (process.platform !== "win32")
- ensurePrivateDirectory(dirname13(paths.socket));
-}
-function readDaemonOwner(paths) {
- try {
- return parseOwner(JSON.parse(readFileSync8(paths.owner, "utf8")));
- } catch (error) {
- if (error instanceof Error)
- return null;
- throw error;
- }
-}
-function writeDaemonOwner(paths, owner) {
- writePrivateFile(paths.pid, `${owner.pid}
-`);
- writePrivateFile(paths.endpoint, owner.endpoint.path);
- writePrivateFile(paths.owner, `${JSON.stringify(owner)}
-`);
-}
-function removeDaemonMetadataForOwner(paths, owner) {
- const current = readDaemonOwner(paths);
- if (!current || !sameOwner(current, owner))
- return;
- unlinkQuietly(paths.socket);
- unlinkQuietly(paths.pid);
- unlinkQuietly(paths.endpoint);
- unlinkQuietly(paths.owner);
-}
-function endpointIdentity(endpointPath) {
- if (process.platform === "win32")
- return { kind: "windows", path: endpointPath };
- try {
- const stats = statSync5(endpointPath);
- return { kind: "unix", path: endpointPath, dev: stats.dev, ino: stats.ino };
- } catch (error) {
- if (error instanceof Error)
- return { kind: "missing", path: endpointPath };
- throw error;
- }
-}
-function sameEndpoint(a, b) {
- if (a.kind !== b.kind || a.path !== b.path)
- return false;
- switch (a.kind) {
- case "unix":
- return b.kind === "unix" && a.dev === b.dev && a.ino === b.ino;
- case "windows":
- return true;
- case "missing":
- return true;
- }
-}
-function sameOwner(a, b) {
- return a.pid === b.pid && a.nonce === b.nonce && sameEndpoint(a.endpoint, b.endpoint);
-}
-async function validateExistingOwner(paths, pingOwner) {
- let token = readOrCreateAuthToken(paths);
- for (let attempt = 0;attempt < 2; attempt += 1) {
- const owner = readDaemonOwner(paths);
- if (!owner)
- return token;
- const ping = await pingOwner(token);
- if (ping && owner.nonce === ping.nonce && sameEndpoint(owner.endpoint, ping.endpoint)) {
- throw new DaemonAlreadyRunningError("LSP daemon already running");
- }
- if (ping)
- continue;
- if (isProcessAlive2(owner.pid))
- throw new DaemonStartupDeferredError("owner_pid_live_unreachable");
- const reread = readDaemonOwner(paths);
- if (!reread || !sameOwner(reread, owner)) {
- throw new DaemonStartupDeferredError("owner_changed_during_cleanup");
- }
- cleanupDeadOwner(paths, owner);
- token = rotateAuthToken(paths);
- return token;
- }
- throw new DaemonStartupDeferredError("reachable_owner_mismatch");
-}
-function cleanupDeadOwner(paths, owner) {
- if (process.platform !== "win32" && existsSync14(owner.endpoint.path)) {
- const stat = lstatSync7(owner.endpoint.path);
- if (stat.isSocket())
- unlinkSync4(owner.endpoint.path);
- }
- unlinkQuietly(paths.pid);
- unlinkQuietly(paths.endpoint);
- unlinkQuietly(paths.owner);
-}
-function newOwner(paths) {
- return {
- pid: process.pid,
- nonce: randomUUID(),
- startedAt: new Date().toISOString(),
- endpoint: endpointIdentity(paths.socket)
- };
-}
-function parseOwner(value) {
- if (!value || typeof value !== "object" || Array.isArray(value))
- return null;
- const pid = Reflect.get(value, "pid");
- const nonce = Reflect.get(value, "nonce");
- const startedAt = Reflect.get(value, "startedAt");
- const endpoint = parseEndpoint(Reflect.get(value, "endpoint"));
- if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string" || !endpoint)
- return null;
- return { pid, nonce, startedAt, endpoint };
-}
-function parseEndpoint(value) {
- if (!value || typeof value !== "object" || Array.isArray(value))
- return null;
- const kind = Reflect.get(value, "kind");
- const path = Reflect.get(value, "path");
- if (typeof path !== "string")
- return null;
- if (kind === undefined)
- return endpointIdentity(path);
- if (kind === "windows")
- return { kind, path };
- if (kind === "missing")
- return { kind, path };
- const dev = Reflect.get(value, "dev");
- const ino = Reflect.get(value, "ino");
- if (kind === "unix" && typeof dev === "number" && typeof ino === "number")
- return { kind, path, dev, ino };
- return null;
-}
-
// src/version-reap.ts
import { execFile } from "node:child_process";
import { readdir, readFile, rm } from "node:fs/promises";
@@ -6919,7 +6950,7 @@ async function attestDaemonCliProcess(pid, platform, deps = {}) {
async function reapStaleDaemonVersions(ownPaths, deps = {}) {
const baseDir = dirname14(ownPaths.dir);
const platform = deps.platform ?? process.platform;
- const isAlive = deps.isAlive ?? isProcessAlive2;
+ const isAlive = deps.isAlive ?? isProcessAlive;
const attest = deps.attest ?? ((pid) => attestDaemonCliProcess(pid, platform));
const sendSignal = deps.sendSignal ?? defaultSendSignal;
const waitForExit = deps.waitForExit ?? defaultWaitForExit;
@@ -7059,7 +7090,7 @@ function defaultSendSignal(pid, signal) {
async function defaultWaitForExit(pid, timeoutMs) {
const deadline = Date.now() + timeoutMs;
for (;; ) {
- if (!isProcessAlive2(pid))
+ if (!isProcessAlive(pid))
return true;
if (Date.now() >= deadline)
return false;
@@ -7229,7 +7260,12 @@ async function main() {
process.exitCode = 2;
}
main().catch((error) => {
- stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}
+ if (error instanceof DaemonStartupDeferredError) {
+ stderr.write(`[lsp-daemon] startup deferred: ${error.reason}
+`);
+ } else {
+ stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}
`);
+ }
process.exitCode = 1;
});
diff --git a/plugins/omo/components/lsp-daemon/dist/client.js b/plugins/omo/components/lsp-daemon/dist/client.js
index fd2da170..b5734805 100644
--- a/plugins/omo/components/lsp-daemon/dist/client.js
+++ b/plugins/omo/components/lsp-daemon/dist/client.js
@@ -6,6 +6,7 @@ import { isAbsolute as isAbsolute6 } from "node:path";
import { connect } from "node:net";
import { homedir as homedir3 } from "node:os";
import { join as join8 } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
@@ -645,9 +646,11 @@ function createLineDecoder(onMessage, onParseError) {
}
// src/ensure-daemon.ts
-var PROBE_TIMEOUT_MS = 500;
+var PROBE_TIMEOUT_MS = 2000;
var DEFAULT_READY_TIMEOUT_MS = 5000;
var DEFAULT_POLL_INTERVAL_MS = 100;
+var FAILED_SPAWN_COOLDOWN_MS = 5000;
+var failedSpawnUntil = new Map;
class DaemonUnreachableError extends Error {
constructor(socketPath) {
@@ -660,11 +663,22 @@ async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), opti
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const signal = options.signal;
throwIfAborted(signal);
- if (await awaitWithSignal(deps.probe(paths, signal), signal))
+ if (await awaitWithSignal(deps.probe(paths, signal), signal)) {
+ failedSpawnUntil.delete(paths.socket);
return;
+ }
throwIfAborted(signal);
+ const retryAt = failedSpawnUntil.get(paths.socket);
+ if (retryAt !== undefined && deps.now() < retryAt)
+ throw new DaemonUnreachableError(paths.socket);
+ failedSpawnUntil.delete(paths.socket);
deps.spawnDaemon(paths);
- await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ try {
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ } catch (error) {
+ failedSpawnUntil.set(paths.socket, deps.now() + FAILED_SPAWN_COOLDOWN_MS);
+ throw error;
+ }
}
async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal) {
const deadline = deps.now() + readyTimeoutMs;
@@ -6332,6 +6346,7 @@ function parseContext(value) {
// src/daemon-client.ts
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
+var STARTUP_BACKOFF_MS = [0, 100, 300];
var nextProxyRequestId = 1;
async function callToolViaDaemon(name, args, options) {
const context = requireContext(options.context);
@@ -6339,17 +6354,31 @@ async function callToolViaDaemon(name, args, options) {
const ensure = options.ensure ?? ((ensurePaths, signal) => ensureDaemonRunning(ensurePaths, undefined, signal === undefined ? {} : { signal }));
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const requestArgs = withContext(args, context);
+ const probe = options.probe ?? ((probePaths, signal) => probeDaemon(probePaths, undefined, signal));
+ const sleep = options.sleep ?? ((ms, signal) => delay(ms, undefined, { signal }));
let lastError;
let authRefreshUsed = false;
- for (let attempt = 0;attempt < 3; attempt += 1) {
+ for (const [attempt, backoffMs] of STARTUP_BACKOFF_MS.entries()) {
try {
- await ensureDaemonAvailable(paths, ensure, options.signal);
+ if (backoffMs > 0)
+ await sleep(backoffMs, options.signal);
+ if (options.signal?.aborted)
+ throw new DaemonRequestCancelledError(false);
+ if (attempt === 0) {
+ await ensureDaemonAvailable(paths, ensure, options.signal);
+ } else if (!await probe(paths, options.signal)) {
+ throw new DaemonUnreachableError(paths.socket);
+ }
const token = readAuthToken(paths);
if (!token)
throw new DaemonRequestError("daemon auth token missing", false);
const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
+ if (options.signal?.aborted) {
+ lastError = new DaemonRequestCancelledError(false);
+ break;
+ }
lastError = error;
if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
authRefreshUsed = true;
diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts b/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts
index 4be32536..ffc0e144 100644
--- a/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts
@@ -8,6 +8,8 @@ export interface CallToolOptions {
requestTimeoutMs?: number;
signal?: AbortSignal;
ensure?: (paths: DaemonPaths, signal?: AbortSignal) => Promise<void>;
+ probe?: (paths: DaemonPaths, signal?: AbortSignal) => Promise<boolean>;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
}
export declare function callToolViaDaemon(name: string, args: Record<string, unknown>, options: CallToolOptions): Promise<ToolExecutionResult>;
export declare function callDiagnosticsViaDaemon(filePath: string, options: CallToolOptions): Promise<ToolExecutionResult>;
diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-client.js b/plugins/omo/components/lsp-daemon/dist/daemon-client.js
index 1ce0441b..2d452156 100644
--- a/plugins/omo/components/lsp-daemon/dist/daemon-client.js
+++ b/plugins/omo/components/lsp-daemon/dist/daemon-client.js
@@ -1,16 +1,18 @@
import { connect } from "node:net";
import { homedir } from "node:os";
import { join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
import { parseLspRequestContext } from "@oh-my-opencode/lsp-core/request-context";
import { isPlainRecord } from "@oh-my-opencode/mcp-stdio-core/record";
import { daemonFailureResult } from "./daemon-failure-result.js";
import { DaemonAuthenticationRejectedError, DaemonRequestCancelledError, DaemonRequestError, DaemonRequestTimedOutError, } from "./daemon-request-error.js";
-import { ensureDaemonRunning } from "./ensure-daemon.js";
+import { DaemonUnreachableError, ensureDaemonRunning, probeDaemon } from "./ensure-daemon.js";
import { authEnvelope, isAuthErrorResponse, readAuthToken } from "./ipc-protocol.js";
import { daemonPaths } from "./paths.js";
import { CONTEXT_KEY } from "./request-routing.js";
import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
+const STARTUP_BACKOFF_MS = [0, 100, 300];
let nextProxyRequestId = 1;
export async function callToolViaDaemon(name, args, options) {
const context = requireContext(options.context);
@@ -19,11 +21,22 @@ export async function callToolViaDaemon(name, args, options) {
((ensurePaths, signal) => ensureDaemonRunning(ensurePaths, undefined, signal === undefined ? {} : { signal }));
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const requestArgs = withContext(args, context);
+ const probe = options.probe ?? ((probePaths, signal) => probeDaemon(probePaths, undefined, signal));
+ const sleep = options.sleep ?? ((ms, signal) => delay(ms, undefined, { signal }));
let lastError;
let authRefreshUsed = false;
- for (let attempt = 0; attempt < 3; attempt += 1) {
+ for (const [attempt, backoffMs] of STARTUP_BACKOFF_MS.entries()) {
try {
- await ensureDaemonAvailable(paths, ensure, options.signal);
+ if (backoffMs > 0)
+ await sleep(backoffMs, options.signal);
+ if (options.signal?.aborted)
+ throw new DaemonRequestCancelledError(false);
+ if (attempt === 0) {
+ await ensureDaemonAvailable(paths, ensure, options.signal);
+ }
+ else if (!(await probe(paths, options.signal))) {
+ throw new DaemonUnreachableError(paths.socket);
+ }
const token = readAuthToken(paths);
if (!token)
throw new DaemonRequestError("daemon auth token missing", false);
@@ -31,6 +44,10 @@ export async function callToolViaDaemon(name, args, options) {
return await sendToolCall(paths, token, name, requestArgs, sendOptions);
}
catch (error) {
+ if (options.signal?.aborted) {
+ lastError = new DaemonRequestCancelledError(false);
+ break;
+ }
lastError = error;
if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
authRefreshUsed = true;
diff --git a/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js b/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js
index cc61578f..a4770318 100644
--- a/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js
+++ b/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js
@@ -8,9 +8,11 @@ import { packagedRuntimeDefaults } from "./paths.js";
import { resolveDaemonRuntime } from "./runtime-contract.js";
import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";
export { InvalidRuntimeOverrideError, OMO_LSP_DAEMON_CLI, resolveDaemonRuntime } from "./runtime-contract.js";
-const PROBE_TIMEOUT_MS = 500;
+const PROBE_TIMEOUT_MS = 2_000;
const DEFAULT_READY_TIMEOUT_MS = 5_000;
const DEFAULT_POLL_INTERVAL_MS = 100;
+const FAILED_SPAWN_COOLDOWN_MS = 5_000;
+const failedSpawnUntil = new Map();
export class DaemonUnreachableError extends Error {
constructor(socketPath) {
super(`LSP daemon did not become reachable at ${socketPath}`);
@@ -22,11 +24,23 @@ export async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const signal = options.signal;
throwIfAborted(signal);
- if (await awaitWithSignal(deps.probe(paths, signal), signal))
+ if (await awaitWithSignal(deps.probe(paths, signal), signal)) {
+ failedSpawnUntil.delete(paths.socket);
return;
+ }
throwIfAborted(signal);
+ const retryAt = failedSpawnUntil.get(paths.socket);
+ if (retryAt !== undefined && deps.now() < retryAt)
+ throw new DaemonUnreachableError(paths.socket);
+ failedSpawnUntil.delete(paths.socket);
deps.spawnDaemon(paths);
- await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ try {
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ }
+ catch (error) {
+ failedSpawnUntil.set(paths.socket, deps.now() + FAILED_SPAWN_COOLDOWN_MS);
+ throw error;
+ }
}
async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal) {
const deadline = deps.now() + readyTimeoutMs;
diff --git a/plugins/omo/components/lsp-daemon/dist/index.js b/plugins/omo/components/lsp-daemon/dist/index.js
index ec636f82..c1fb46ab 100644
--- a/plugins/omo/components/lsp-daemon/dist/index.js
+++ b/plugins/omo/components/lsp-daemon/dist/index.js
@@ -3150,6 +3150,7 @@ async function disposeDefaultLspManager() {
import { connect } from "node:net";
import { homedir as homedir3 } from "node:os";
import { join as join8 } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
@@ -3789,9 +3790,11 @@ function createLineDecoder(onMessage, onParseError) {
}
// src/ensure-daemon.ts
-var PROBE_TIMEOUT_MS = 500;
+var PROBE_TIMEOUT_MS = 2000;
var DEFAULT_READY_TIMEOUT_MS = 5000;
var DEFAULT_POLL_INTERVAL_MS = 100;
+var FAILED_SPAWN_COOLDOWN_MS = 5000;
+var failedSpawnUntil = new Map;
class DaemonUnreachableError extends Error {
constructor(socketPath) {
@@ -3804,11 +3807,22 @@ async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), opti
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const signal = options.signal;
throwIfAborted(signal);
- if (await awaitWithSignal2(deps.probe(paths, signal), signal))
+ if (await awaitWithSignal2(deps.probe(paths, signal), signal)) {
+ failedSpawnUntil.delete(paths.socket);
return;
+ }
throwIfAborted(signal);
+ const retryAt = failedSpawnUntil.get(paths.socket);
+ if (retryAt !== undefined && deps.now() < retryAt)
+ throw new DaemonUnreachableError(paths.socket);
+ failedSpawnUntil.delete(paths.socket);
deps.spawnDaemon(paths);
- await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ try {
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ } catch (error) {
+ failedSpawnUntil.set(paths.socket, deps.now() + FAILED_SPAWN_COOLDOWN_MS);
+ throw error;
+ }
}
async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal) {
const deadline = deps.now() + readyTimeoutMs;
@@ -6327,6 +6341,7 @@ function parseContext(value) {
// src/daemon-client.ts
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
+var STARTUP_BACKOFF_MS = [0, 100, 300];
var nextProxyRequestId = 1;
async function callToolViaDaemon(name, args, options) {
const context = requireContext(options.context);
@@ -6334,17 +6349,31 @@ async function callToolViaDaemon(name, args, options) {
const ensure = options.ensure ?? ((ensurePaths, signal) => ensureDaemonRunning(ensurePaths, undefined, signal === undefined ? {} : { signal }));
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const requestArgs = withContext(args, context);
+ const probe = options.probe ?? ((probePaths, signal) => probeDaemon(probePaths, undefined, signal));
+ const sleep = options.sleep ?? ((ms, signal) => delay(ms, undefined, { signal }));
let lastError;
let authRefreshUsed = false;
- for (let attempt = 0;attempt < 3; attempt += 1) {
+ for (const [attempt, backoffMs] of STARTUP_BACKOFF_MS.entries()) {
try {
- await ensureDaemonAvailable(paths, ensure, options.signal);
+ if (backoffMs > 0)
+ await sleep(backoffMs, options.signal);
+ if (options.signal?.aborted)
+ throw new DaemonRequestCancelledError(false);
+ if (attempt === 0) {
+ await ensureDaemonAvailable(paths, ensure, options.signal);
+ } else if (!await probe(paths, options.signal)) {
+ throw new DaemonUnreachableError(paths.socket);
+ }
const token = readAuthToken(paths);
if (!token)
throw new DaemonRequestError("daemon auth token missing", false);
const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
+ if (options.signal?.aborted) {
+ lastError = new DaemonRequestCancelledError(false);
+ break;
+ }
lastError = error;
if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
authRefreshUsed = true;
diff --git a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json
index ba3e68e7..3769bec1 100644
--- a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json
+++ b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
- "version": "5.0.0-beta.80",
- "inputDigest": "sha256:4c3ae4939cef82bfbc66b27a58b66f2585d1ca4520dd51f0b3e42540270af7ae",
+ "version": "5.0.0-beta.81",
+ "inputDigest": "sha256:319828ab37967b4cd77e0a52d4e5d4bada4acea967ec72506e9540f604e56e0d",
"outputs": [
{
"path": "cli.d.ts",
@@ -9,7 +9,7 @@
},
{
"path": "cli.js",
- "sha256": "b8d0f009e0031d015280244ddd2e5abb8db076ffb324c7e500d29d437a345446"
+ "sha256": "a0155ce31758825f26a35acbc894361e22a6531bab3fc47bc1f5c2ed054580ef"
},
{
"path": "codex-hook-cli.d.ts",
diff --git a/plugins/omo/components/lsp/dist/cli.js b/plugins/omo/components/lsp/dist/cli.js
index c8d8e390..c3ac0b30 100644
--- a/plugins/omo/components/lsp/dist/cli.js
+++ b/plugins/omo/components/lsp/dist/cli.js
@@ -16,6 +16,7 @@ import { join as join11, resolve as resolve11 } from "node:path";
import { statSync as statSync5 } from "node:fs";
import { isAbsolute as isAbsolute6 } from "node:path";
import { connect } from "node:net";
+import { setTimeout as delay } from "node:timers/promises";
import { AsyncLocalStorage } from "node:async_hooks";
import { existsSync, realpathSync, statSync } from "node:fs";
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
@@ -482,9 +483,11 @@ function createLineDecoder(onMessage, onParseError) {
}
};
}
-var PROBE_TIMEOUT_MS = 500;
+var PROBE_TIMEOUT_MS = 2000;
var DEFAULT_READY_TIMEOUT_MS = 5000;
var DEFAULT_POLL_INTERVAL_MS = 100;
+var FAILED_SPAWN_COOLDOWN_MS = 5000;
+var failedSpawnUntil = new Map;
class DaemonUnreachableError extends Error {
constructor(socketPath) {
@@ -497,11 +500,22 @@ async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), opti
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const signal = options.signal;
throwIfAborted(signal);
- if (await awaitWithSignal(deps.probe(paths, signal), signal))
+ if (await awaitWithSignal(deps.probe(paths, signal), signal)) {
+ failedSpawnUntil.delete(paths.socket);
return;
+ }
throwIfAborted(signal);
+ const retryAt = failedSpawnUntil.get(paths.socket);
+ if (retryAt !== undefined && deps.now() < retryAt)
+ throw new DaemonUnreachableError(paths.socket);
+ failedSpawnUntil.delete(paths.socket);
deps.spawnDaemon(paths);
- await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ try {
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal);
+ } catch (error) {
+ failedSpawnUntil.set(paths.socket, deps.now() + FAILED_SPAWN_COOLDOWN_MS);
+ throw error;
+ }
}
async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs, signal) {
const deadline = deps.now() + readyTimeoutMs;
@@ -5544,6 +5558,7 @@ var LSP_MCP_TOOLS = [
];
var CONTEXT_KEY = "_context";
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
+var STARTUP_BACKOFF_MS = [0, 100, 300];
var nextProxyRequestId = 1;
async function callToolViaDaemon(name, args, options) {
const context = requireContext(options.context);
@@ -5551,17 +5566,31 @@ async function callToolViaDaemon(name, args, options) {
const ensure = options.ensure ?? ((ensurePaths, signal) => ensureDaemonRunning(ensurePaths, undefined, signal === undefined ? {} : { signal }));
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const requestArgs = withContext(args, context);
+ const probe = options.probe ?? ((probePaths, signal) => probeDaemon(probePaths, undefined, signal));
+ const sleep = options.sleep ?? ((ms, signal) => delay(ms, undefined, { signal }));
let lastError;
let authRefreshUsed = false;
- for (let attempt = 0;attempt < 3; attempt += 1) {
+ for (const [attempt, backoffMs] of STARTUP_BACKOFF_MS.entries()) {
try {
- await ensureDaemonAvailable(paths, ensure, options.signal);
+ if (backoffMs > 0)
+ await sleep(backoffMs, options.signal);
+ if (options.signal?.aborted)
+ throw new DaemonRequestCancelledError(false);
+ if (attempt === 0) {
+ await ensureDaemonAvailable(paths, ensure, options.signal);
+ } else if (!await probe(paths, options.signal)) {
+ throw new DaemonUnreachableError(paths.socket);
+ }
const token = readAuthToken(paths);
if (!token)
throw new DaemonRequestError("daemon auth token missing", false);
const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
+ if (options.signal?.aborted) {
+ lastError = new DaemonRequestCancelledError(false);
+ break;
+ }
lastError = error;
if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
authRefreshUsed = true;
diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.json
index f8ceb4ef..28a1b7eb 100644
--- a/plugins/omo/components/lsp/hooks/hooks.json
+++ b/plugins/omo/components/lsp/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 60,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking LSP Diagnostics"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking LSP Diagnostics"
}
]
}
@@ -21,7 +21,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Resetting LSP Diagnostics Cache"
+ "statusMessage": "(OmO 5.0.0-beta.81) Resetting LSP Diagnostics Cache"
}
]
}
diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.json
index 33d659ec..5335a083 100644
--- a/plugins/omo/components/lsp/package.json
+++ b/plugins/omo/components/lsp/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-lsp",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.",
"type": "module",
"packageManager": "[email protected]",
@@ -54,10 +54,11 @@
"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@vitest/coverage-v8": "5.0.1",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.json
index 134745b5..812416af 100644
--- a/plugins/omo/components/rules/hooks/hooks.json
+++ b/plugins/omo/components/rules/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Loading Project Rules"
+ "statusMessage": "(OmO 5.0.0-beta.81) Loading Project Rules"
}
]
}
@@ -19,7 +19,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Loading Project Rules"
+ "statusMessage": "(OmO 5.0.0-beta.81) Loading Project Rules"
}
]
}
@@ -32,7 +32,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Matching Project Rules"
+ "statusMessage": "(OmO 5.0.0-beta.81) Matching Project Rules"
}
]
}
@@ -45,7 +45,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Resetting Project Rule Cache"
+ "statusMessage": "(OmO 5.0.0-beta.81) Resetting Project Rule Cache"
}
]
}
diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.json
index 70850aef..294513e1 100644
--- a/plugins/omo/components/rules/package.json
+++ b/plugins/omo/components/rules/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-rules",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex plugin that injects project rule files into model context through lifecycle hooks.",
"type": "module",
"packageManager": "[email protected]",
@@ -50,12 +50,13 @@
"picomatch": "^4.0.7"
},
"devDependencies": {
+ "@vitest/coverage-v8": "5.0.1",
"@oh-my-opencode/rules-engine": "file:../../../../rules-engine",
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"@types/picomatch": "^4.0.3",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/teammode/hooks/hooks.json b/plugins/omo/components/teammode/hooks/hooks.json
index b2dcbbb5..addeee61 100644
--- a/plugins/omo/components/teammode/hooks/hooks.json
+++ b/plugins/omo/components/teammode/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Thread Title Hygiene"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Thread Title Hygiene"
}
]
}
diff --git a/plugins/omo/components/teammode/package.json b/plugins/omo/components/teammode/package.json
index 3bb12f01..78e0f48a 100644
--- a/plugins/omo/components/teammode/package.json
+++ b/plugins/omo/components/teammode/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-teammode",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex team-mode hook component that keeps background thread titles descriptive after create_thread.",
"type": "module",
"private": true,
@@ -15,10 +15,11 @@
"typecheck": "tsc --noEmit"
},
"devDependencies": {
- "@types/node": "^26.2.0",
+ "@vitest/coverage-v8": "5.0.1",
+ "@types/node": "^26.6.2",
"bun-types": "^1.4.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/telemetry/dist/cli.js b/plugins/omo/components/telemetry/dist/cli.js
index ae7d4299..2fc03a09 100755
--- a/plugins/omo/components/telemetry/dist/cli.js
+++ b/plugins/omo/components/telemetry/dist/cli.js
@@ -385,7 +385,7 @@ function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST)
return env["POSTHOG_HOST"]?.trim() || defaultHost;
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
import { dirname as dirname2, posix, sep } from "node:path";
function createModulerModifier() {
const getModuleFromFileName = createGetModuleFromFilename();
@@ -421,139 +421,7 @@ function normalizeWindowsPath(path) {
return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
-var normalizeFlagsResponse = (flagsResponse) => {
- if ("flags" in flagsResponse) {
- const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
- const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads
- };
- }
- {
- const featureFlags = flagsResponse.featureFlags ?? {};
- const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
- k,
- parsePayload(v)
- ]));
- const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
- key,
- getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
- ]));
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads,
- flags
- };
- }
-};
-function getFlagDetailFromFlagAndPayload(key, value, payload) {
- return {
- key,
- enabled: typeof value == "string" ? true : value,
- variant: typeof value == "string" ? value : undefined,
- reason: undefined,
- metadata: {
- id: undefined,
- version: undefined,
- payload: payload ? JSON.stringify(payload) : undefined,
- description: undefined
- }
- };
-}
-var getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
- key,
- getFeatureFlagValue(detail)
-]).filter(([, value]) => value !== undefined));
-var getPayloadsFromFlags = (flags) => {
- const safeFlags = flags ?? {};
- return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
- const details = safeFlags[flag];
- return details.enabled && details.metadata && details.metadata.payload !== undefined;
- }).map((flag) => {
- const payload = safeFlags[flag].metadata?.payload;
- return [
- flag,
- payload ? parsePayload(payload) : undefined
- ];
- }));
-};
-var getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled;
-var parsePayload = (response) => {
- if (typeof response != "string")
- return response;
- try {
- return JSON.parse(response);
- } catch {
- return response;
- }
-};
-var MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
- "utm_source",
- "utm_medium",
- "utm_campaign",
- "utm_content",
- "utm_term",
- "gad_source",
- "mc_cid",
- "gclid",
- "gclsrc",
- "dclid",
- "gbraid",
- "wbraid",
- "fbclid",
- "msclkid",
- "twclid",
- "li_fat_id",
- "igshid",
- "ttclid",
- "rdt_cid",
- "epik",
- "qclid",
- "sccid",
- "irclid",
- "_kx"
-];
-var MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
- "$feature_flag",
- "$feature_flag_response",
- "$feature_flag_has_experiment",
- "$feature_flag_id",
- "$feature_flag_version",
- "$feature_flag_reason",
- "$feature_flag_request_id",
- "$feature_flag_evaluated_at",
- "$feature_flag_error",
- "locally_evaluated",
- "$groups",
- "$process_person_profile",
- "$geoip_disable",
- "$current_url",
- "$pathname",
- "$referring_domain",
- ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
- "$session_id",
- "$window_id",
- "$lib",
- "$lib_version",
- "$device_id",
- "$is_server"
-];
-var minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
- const minimal = {};
- const copyKey = (key) => {
- if (properties[key] !== undefined)
- minimal[key] = properties[key];
- };
- MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
- transportKeys.forEach(copyKey);
- return minimal;
-};
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
PostHogPersistedProperty["DistinctId"] = "distinct_id";
@@ -583,6 +451,7 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
PostHogPersistedProperty["PushRegistered"] = "push_registered";
PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
+ PostHogPersistedProperty["SurveysInProgress"] = "surveys_in_progress";
PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
PostHogPersistedProperty["Surveys"] = "surveys";
PostHogPersistedProperty["RemoteConfig"] = "remote_config";
@@ -591,108 +460,80 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
return PostHogPersistedProperty;
}({});
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
-function isGzipSupported() {
- return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
+function safeJsonStringify(value) {
+ const ancestors = [];
+ return JSON.stringify(value, function(_key, replacementValue) {
+ if (typeof replacementValue == "bigint")
+ return replacementValue.toString();
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
+ return;
+ if (replacementValue instanceof Error)
+ return {
+ name: replacementValue.name,
+ message: replacementValue.message,
+ stack: replacementValue.stack
+ };
+ if (replacementValue && typeof replacementValue == "object") {
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
+ ancestors.pop();
+ if (ancestors.includes(replacementValue))
+ return "[Circular]";
+ ancestors.push(replacementValue);
+ }
+ return replacementValue;
+ }) ?? "null";
}
-var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError";
-var GZIP_MAGIC_FIRST_BYTE = 31;
-var GZIP_MAGIC_SECOND_BYTE = 139;
-var GZIP_DEFLATE_METHOD = 8;
-var hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;
-var crc32Table;
-var getCrc32Table = () => {
- if (crc32Table)
- return crc32Table;
- crc32Table = [];
- for (let i = 0;i < 256; i++) {
- let crc = i;
- for (let j = 0;j < 8; j++)
- crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
- crc32Table[i] = crc >>> 0;
- }
- return crc32Table;
-};
-var crc32 = (bytes) => {
- const table = getCrc32Table();
- let crc = 4294967295;
- for (let i = 0;i < bytes.length; i++)
- crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
- return (4294967295 ^ crc) >>> 0;
-};
-var throwNativeGzipValidationError = (reason) => {
- const error = new Error(`Native gzip produced invalid output: ${reason}`);
- error.name = NATIVE_GZIP_VALIDATION_ERROR;
- throw error;
-};
-var validateNativeGzip = async (compressed, inputBytes) => {
- if (compressed.size < 18)
- throwNativeGzipValidationError("too-short");
- const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
- if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
- throwNativeGzipValidationError("invalid-header");
- const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
- if (trailer.getUint32(0, true) !== crc32(inputBytes))
- throwNativeGzipValidationError("invalid-crc");
- const inputSize = inputBytes.length >>> 0;
- if (trailer.getUint32(4, true) !== inputSize)
- throwNativeGzipValidationError("invalid-size");
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
+var nativeIsArray = Array.isArray;
+var ObjProto = Object.prototype;
+var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
+var type_utils_toString = ObjProto.toString;
+var isArray = nativeIsArray || function(obj) {
+ return type_utils_toString.call(obj) === "[object Array]";
};
-async function gzipCompress(input, isDebug = true, options) {
- try {
- const inputBytes = new TextEncoder().encode(input);
- const compressedStream = new globalThis.CompressionStream("gzip");
- const writer = compressedStream.writable.getWriter();
- const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
- try {
- await writer.abort(err);
- } catch {}
- throw err;
- });
- const responsePromise = new Response(compressedStream.readable).blob();
- const [compressed] = await Promise.all([
- responsePromise,
- writePromise
- ]);
- await validateNativeGzip(compressed, inputBytes);
- return compressed;
- } catch (error) {
- if (options?.rethrow)
- throw error;
- if (isDebug)
- console.error("Failed to gzip compress data", error);
- return null;
+var isObject = (x) => x === Object(x) && !isArray(x);
+var isUndefined = (x) => x === undefined;
+var isString = (x) => type_utils_toString.call(x) == "[object String]";
+var isEmptyString = (x) => isString(x) && x.trim().length === 0;
+var isNull = (x) => x === null;
+var isNullish = (x) => isUndefined(x) || isNull(x);
+var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
+var isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
+function isPrimitive(value) {
+ return value === null || typeof value != "object";
+}
+function isBuiltin(candidate, className) {
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
+}
+function isError(candidate) {
+ switch (Object.prototype.toString.call(candidate)) {
+ case "[object Error]":
+ case "[object Exception]":
+ case "[object DOMException]":
+ case "[object DOMError]":
+ case "[object WebAssembly.Exception]":
+ return true;
+ default:
+ return isInstanceOf(candidate, Error);
}
}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
-var MAX_JSON_SAFE_VALUE_DEPTH = 20;
-var MAX_JSON_SAFE_VALUE_ITEMS = 1000;
-var MAX_JSON_SAFE_VALUE_NODES = 1e4;
-var CIRCULAR_VALUE = "[Circular]";
-var TRUNCATED_VALUE = "[Truncated]";
-var UNSERIALIZABLE_VALUE = "[Unserializable]";
-var FUNCTION_VALUE = "[Function]";
-var dateGetTime = Date.prototype.getTime;
-var dateToISOString = Date.prototype.toISOString;
-function sanitizeString(value) {
- let output = "";
- for (let index = 0;index < value.length; index++) {
- const codeUnit = value.charCodeAt(index);
- if (codeUnit >= 55296 && codeUnit <= 56319) {
- const nextCodeUnit = value.charCodeAt(index + 1);
- if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
- output += value[index] + value[index + 1];
- index++;
- } else
- output += "�";
- } else
- output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
+function isEvent(candidate) {
+ return "u" > typeof Event && isInstanceOf(candidate, Event);
+}
+function isPlainObject(candidate) {
+ return isBuiltin(candidate, "Object");
+}
+function isInstanceOf(candidate, base) {
+ try {
+ return candidate instanceof base;
+ } catch {
+ return false;
}
- return output;
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
var DEFAULT_BLOCKED_UA_STRS = [
"amazonbot",
"amazonproductbot",
@@ -720,7 +561,7 @@ var DEFAULT_BLOCKED_UA_STRS = [
"msnbot",
"nessus",
"petalbot",
- "pinterest",
+ "pinterestbot",
"prerender",
"rogerbot",
"screaming frog",
@@ -781,79 +622,7 @@ var isBlockedUA = function(ua, customBlockedUserAgents = []) {
return uaLower.indexOf(blockedUaLower) !== -1;
});
};
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
-function safeJsonStringify(value) {
- const ancestors = [];
- return JSON.stringify(value, function(_key, replacementValue) {
- if (typeof replacementValue == "bigint")
- return replacementValue.toString();
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
- return;
- if (replacementValue instanceof Error)
- return {
- name: replacementValue.name,
- message: replacementValue.message,
- stack: replacementValue.stack
- };
- if (replacementValue && typeof replacementValue == "object") {
- while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
- ancestors.pop();
- if (ancestors.includes(replacementValue))
- return "[Circular]";
- ancestors.push(replacementValue);
- }
- return replacementValue;
- }) ?? "null";
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
-var nativeIsArray = Array.isArray;
-var ObjProto = Object.prototype;
-var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
-var type_utils_toString = ObjProto.toString;
-var isArray = nativeIsArray || function(obj) {
- return type_utils_toString.call(obj) === "[object Array]";
-};
-var isObject = (x) => x === Object(x) && !isArray(x);
-var isUndefined = (x) => x === undefined;
-var isString = (x) => type_utils_toString.call(x) == "[object String]";
-var isEmptyString = (x) => isString(x) && x.trim().length === 0;
-var isNull = (x) => x === null;
-var isNullish = (x) => isUndefined(x) || isNull(x);
-var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
-var isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
-function isPrimitive(value) {
- return value === null || typeof value != "object";
-}
-function isBuiltin(candidate, className) {
- return Object.prototype.toString.call(candidate) === `[object ${className}]`;
-}
-function isError(candidate) {
- switch (Object.prototype.toString.call(candidate)) {
- case "[object Error]":
- case "[object Exception]":
- case "[object DOMException]":
- case "[object DOMError]":
- case "[object WebAssembly.Exception]":
- return true;
- default:
- return isInstanceOf(candidate, Error);
- }
-}
-function isEvent(candidate) {
- return typeof Event != "undefined" && isInstanceOf(candidate, Event);
-}
-function isPlainObject(candidate) {
- return isBuiltin(candidate, "Object");
-}
-function isInstanceOf(candidate, base) {
- try {
- return candidate instanceof base;
- } catch {
- return false;
- }
-}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
function clampToRange(value, min, max, logger, fallbackValue) {
if (min > max) {
logger.warn("min cannot be greater than max.");
@@ -870,10 +639,10 @@ function clampToRange(value, min, max, logger, fallbackValue) {
return min;
}
logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
- return clampToRange(fallbackValue || max, min, max, logger);
+ return clampToRange(fallbackValue ?? max, min, max, logger);
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
var ONE_DAY_IN_MS = 86400000;
var DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;
var DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;
@@ -925,8 +694,8 @@ class BucketedRateLimiter {
this._buckets = {};
}
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
-/*! For license information please see uuidv7.mjs.LICENSE.txt */
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
+/*! LICENSE: uuidv7.mjs.LICENSE.txt */
var DIGITS = "0123456789abcdef";
class UUID {
@@ -1097,13 +866,13 @@ class V7Generator {
}
}
var getDefaultRandom = () => ({
- nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random()) >>> 0
});
var defaultGenerator;
var uuidv7 = () => uuidv7obj().toString();
var uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
class PromiseQueue {
add(promise) {
const promiseUUID = uuidv7();
@@ -1141,7 +910,7 @@ class PromiseQueue {
this.nextId = 0;
}
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
function createConsole(consoleLike = console) {
const lockedMethods = {
log: consoleLike.log.bind(consoleLike),
@@ -1182,7 +951,7 @@ var passThrough = (fn) => fn();
function createLogger(prefix, maybeCall = passThrough) {
return _createLogger(prefix, maybeCall, createConsole());
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
var MOBILE = "Mobile";
var IOS = "iOS";
var ANDROID = "Android";
@@ -1225,9 +994,13 @@ var DUCKDUCKGO = "DuckDuckGo";
var PALE_MOON = "Pale Moon";
var WATERFOX = "Waterfox";
var BRAVE = "Brave";
+var CLAUDE = "Claude";
+var CODEX = "Codex";
+var CHATGPT = "ChatGPT";
var GOOGLE_SEARCH_APP = "Google Search App";
var BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)";
var DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
+var AI_APP_VERSION_REGEX = new RegExp("(" + CLAUDE + "|" + CODEX + "|" + CHATGPT + ")\\/" + BROWSER_VERSION_REGEX_SUFFIX);
var XBOX_REGEX = new RegExp(XBOX, "i");
var PLAYSTATION_REGEX = new RegExp(PLAYSTATION + " \\w+", "i");
var NINTENDO_REGEX = new RegExp(NINTENDO + " \\w+", "i");
@@ -1304,6 +1077,15 @@ var versionRegexes = {
[BRAVE]: [
new RegExp(BRAVE + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
+ [CLAUDE]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CODEX]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CHATGPT]: [
+ AI_APP_VERSION_REGEX
+ ],
[DUCKDUCKGO]: [
new RegExp("(DuckDuckGo|Ddg)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
@@ -1474,8 +1256,121 @@ var osMatchers = [
]
]
];
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
+var MAX_JSON_SAFE_VALUE_DEPTH = 20;
+var MAX_JSON_SAFE_VALUE_ITEMS = 1000;
+var MAX_JSON_SAFE_VALUE_NODES = 1e4;
+var CIRCULAR_VALUE = "[Circular]";
+var TRUNCATED_VALUE = "[Truncated]";
+var UNSERIALIZABLE_VALUE = "[Unserializable]";
+var FUNCTION_VALUE = "[Function]";
+var dateGetTime = Date.prototype.getTime;
+var dateToISOString = Date.prototype.toISOString;
+function sanitizeString(value) {
+ let output = "";
+ for (let index = 0;index < value.length; index++) {
+ const codeUnit = value.charCodeAt(index);
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
+ const nextCodeUnit = value.charCodeAt(index + 1);
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
+ output += value[index] + value[index + 1];
+ index++;
+ } else
+ output += "�";
+ } else
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
+ }
+ return output;
+}
+function assignUserAttributes(target, source) {
+ if (!source)
+ return target;
+ let keys = [];
+ try {
+ keys = Object.keys(source);
+ } catch {
+ keys = [];
+ }
+ for (const key of keys) {
+ let value;
+ try {
+ value = source[key];
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ return target;
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/retry-after.mjs
+var MAX_RETRY_AFTER_MS = 300000;
+var CLOCK_STEP_TOLERANCE_MS = 5000;
+function parseRetryAfterMs(value, now = Date.now()) {
+ if (typeof value != "string" || !value)
+ return;
+ const raw = value.trim();
+ const trimmed = /^\d+\s*,/.test(raw) ? raw.slice(0, raw.indexOf(",")).trim() : raw;
+ if (/^\d+$/.test(trimmed)) {
+ const ms = 1000 * Math.min(Number(trimmed), MAX_RETRY_AFTER_MS / 1000);
+ return ms > 0 ? ms : undefined;
+ }
+ if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(trimmed))
+ return;
+ const date = /^\w{3} \w{3} /.test(trimmed) ? trimmed + " GMT" : trimmed;
+ const ms = Date.parse(date) - now;
+ if (!Number.isFinite(ms) || ms <= 0)
+ return;
+ return Math.min(ms, MAX_RETRY_AFTER_MS);
+}
+
+class RetryAfterWindow {
+ record(outcome) {
+ if (outcome.kind === "too-large")
+ return;
+ if (outcome.kind !== "retry-later")
+ return void this.reset();
+ if (!outcome.retryAfterMs)
+ return;
+ const open = this.isOpen();
+ const now = Date.now();
+ const asked = Math.min(outcome.retryAfterMs, MAX_RETRY_AFTER_MS);
+ if (!open) {
+ this._installedAt = now;
+ this._until = now + asked;
+ return;
+ }
+ this._until = Math.max(this._until, Math.min(now + asked, this._installedAt + MAX_RETRY_AFTER_MS));
+ }
+ remainingMs() {
+ const now = Date.now();
+ if (now < this._installedAt - CLOCK_STEP_TOLERANCE_MS) {
+ this.reset();
+ return 0;
+ }
+ const remaining = Math.min(MAX_RETRY_AFTER_MS, Math.max(0, this._until - now));
+ if (remaining === 0)
+ this.reset();
+ return remaining;
+ }
+ isOpen() {
+ return this.remainingMs() > 0;
+ }
+ reset() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+ constructor() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
var STRING_FORMAT = "utf8";
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isValidUUID(value) {
@@ -1484,6 +1379,18 @@ function isValidUUID(value) {
function getEventUuid(uuid, generateUuid) {
return isValidUUID(uuid) ? uuid : generateUuid();
}
+function createNamedError(name, message) {
+ const error = new Error(message);
+ try {
+ Object.defineProperty(error, "name", {
+ value: name,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ } catch {}
+ return error;
+}
function removeTrailingSlash(url) {
return url?.replace(/\/+$/, "");
}
@@ -1531,6 +1438,7 @@ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
clearTimeout(timeoutHandle);
}
}
+var isPromise = (obj) => obj && typeof obj.then == "function";
function allSettled(promises) {
return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
status: "fulfilled",
@@ -1541,2312 +1449,4803 @@ function allSettled(promises) {
}))));
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
-var OTLP_SEVERITY_MAP = {
- trace: {
- text: "TRACE",
- number: 1
- },
- debug: {
- text: "DEBUG",
- number: 5
- },
- info: {
- text: "INFO",
- number: 9
- },
- warn: {
- text: "WARN",
- number: 13
- },
- error: {
- text: "ERROR",
- number: 17
- },
- fatal: {
- text: "FATAL",
- number: 21
- }
-};
-var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
-var INT64_RANGE_LIMIT = 9223372036854776000;
-var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
-function newState() {
- return {
- ancestors: new WeakSet,
- remainingNodes: MAX_JSON_SAFE_VALUE_NODES
- };
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
+var parsedStackResults;
+var lastKeysCount;
+var cachedFilenameChunkIds;
+function getFilenameToChunkIdMap(stackParser) {
+ const chunkIdMap = globalThis._posthogChunkIds;
+ if (!chunkIdMap)
+ return;
+ const chunkIdKeys = Object.keys(chunkIdMap);
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
+ return cachedFilenameChunkIds;
+ lastKeysCount = chunkIdKeys.length;
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
+ if (!parsedStackResults)
+ parsedStackResults = {};
+ const result = parsedStackResults[stackKey];
+ if (result)
+ acc[result[0]] = result[1];
+ else {
+ const parsedStack = stackParser(stackKey);
+ for (let i = parsedStack.length - 1;i >= 0; i--) {
+ const stackFrame = parsedStack[i];
+ const filename = stackFrame?.filename;
+ const chunkId = chunkIdMap[stackKey];
+ if (filename && chunkId) {
+ acc[filename] = chunkId;
+ parsedStackResults[stackKey] = [
+ filename,
+ chunkId
+ ];
+ break;
+ }
+ }
+ }
+ return acc;
+ }, {});
+ return cachedFilenameChunkIds;
}
-function toOtlpKeyValueList(attrs, logger) {
- try {
- return encodeKeyValueList(attrs, logger, newState(), 0);
- } catch {
- return [];
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
+var MAX_EXCEPTIONS = 50;
+var MAX_AGGREGATE_MEMBER_INSPECTIONS = 1000;
+var MAX_ERROR_PROTOTYPE_DEPTH = 100;
+var MAX_WRAPPER_RECURSION = 4;
+
+class ErrorPropertiesBuilder {
+ constructor(coercers, stackParser, modifiers = []) {
+ this.coercers = coercers;
+ this.stackParser = stackParser;
+ this.modifiers = modifiers;
}
-}
-function encodeAnyValue(value, logger, state, depth) {
- if (state.remainingNodes <= 0)
- return {
- stringValue: TRUNCATED_VALUE
+ buildFromUnknown(input, hint = {}) {
+ const providedMechanism = hint && hint.mechanism;
+ const mechanism = providedMechanism || {
+ handled: true,
+ type: "generic"
};
- state.remainingNodes--;
- if (isBoolean(value))
- return {
- boolValue: value
- };
- if (typeof value == "number") {
- if (!Number.isFinite(value))
- return {
- stringValue: String(value)
- };
- if (Number.isInteger(value)) {
- if (Number.isSafeInteger(value))
- return {
- intValue: String(value)
- };
- if (typeof BigInt == "undefined")
- return {
- stringValue: String(value)
- };
- const decimal = BigInt(value).toString();
- if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
- logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
- return {
- stringValue: decimal
- };
- }
- return {
- intValue: decimal
- };
- }
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
+ const exceptionWithCause = coercingContext.apply(input);
+ const parsingContext = this.buildParsingContext(hint);
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
return {
- doubleValue: value
+ $exception_list: exceptionList,
+ $exception_level: "error"
};
}
- if (typeof value == "string")
- return {
- stringValue: sanitizeString(value)
- };
- if (typeof value == "function")
+ async modifyFrames(exceptionList) {
+ for (const exc of exceptionList)
+ if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
+ exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
+ return exceptionList;
+ }
+ coerceFallback(ctx) {
return {
- stringValue: FUNCTION_VALUE
+ type: "Error",
+ value: "Unknown error",
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
};
- if (typeof value == "symbol")
+ }
+ parseStacktrace(err, ctx) {
+ let cause;
+ if (err.cause != null)
+ cause = this.parseStacktrace(err.cause, ctx);
+ let stack;
+ if (err.stack != "" && err.stack != null)
+ try {
+ stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
+ } catch {}
return {
- stringValue: String(value)
+ ...err,
+ cause,
+ stack,
+ errors: err.errors?.map((child) => this.parseStacktrace(child, ctx))
};
- if (typeof value == "object" && value !== null) {
- if (state.ancestors.has(value))
- return {
- stringValue: CIRCULAR_VALUE
- };
- if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
- return {
- stringValue: TRUNCATED_VALUE
+ }
+ applyChunkIds(frames, chunkIdMap) {
+ return frames.map((frame) => {
+ if (frame.filename && chunkIdMap)
+ frame.chunk_id = chunkIdMap[frame.filename];
+ return frame;
+ });
+ }
+ applyCoercers(input, ctx) {
+ for (const adapter of this.coercers)
+ if (adapter.match(input))
+ return adapter.coerce(input, ctx);
+ return this.coerceFallback(ctx);
+ }
+ async applyModifiers(frames) {
+ let newFrames = frames;
+ for (const modifier of this.modifiers)
+ newFrames = await modifier(newFrames);
+ return newFrames;
+ }
+ convertToExceptionList(exceptionWithStack, mechanism) {
+ const exceptionList = [];
+ const append = (exception, parentId, source) => {
+ const exceptionId = exceptionList.length;
+ const entryMechanism = parentId === undefined ? {
+ type: typeof mechanism.type == "string" && mechanism.type.length > 0 ? mechanism.type : "generic",
+ ...typeof mechanism.handled == "boolean" ? {
+ handled: mechanism.handled
+ } : mechanism.handled === undefined ? {
+ handled: true
+ } : {},
+ synthetic: typeof mechanism.synthetic == "boolean" ? mechanism.synthetic : exception.synthetic,
+ exception_id: exceptionId
+ } : {
+ type: "chained",
+ source,
+ synthetic: exception.synthetic,
+ exception_id: exceptionId,
+ parent_id: parentId
};
- if (value instanceof Date) {
- const time = value.getTime();
- const iso = Number.isFinite(time) ? value.toISOString() : String(value);
- return {
- stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ const currentException = {
+ type: exception.type,
+ value: exception.value,
+ mechanism: entryMechanism
};
- }
- state.ancestors.add(value);
+ if (exception.stack)
+ currentException.stacktrace = {
+ type: "raw",
+ frames: exception.stack
+ };
+ exceptionList.push(currentException);
+ if (exception.cause)
+ append(exception.cause, exceptionId, "cause");
+ for (const child of exception.errors ?? [])
+ append(child, exceptionId, "member");
+ };
+ append(exceptionWithStack);
+ return exceptionList;
+ }
+ buildParsingContext(hint) {
+ const context = {
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
+ skipFirstLines: hint.skipFirstLines ?? 1
+ };
+ return context;
+ }
+ getAggregateErrors(input) {
try {
- try {
- const toJSON = value.toJSON;
- if (typeof toJSON == "function")
- return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
- } catch {}
- if (isArray(value))
- return {
- arrayValue: {
- values: encodeArrayValues(value, logger, state, depth + 1)
+ if (isError(input)) {
+ let prototype = Object.getPrototypeOf(input);
+ for (let depth = 0;prototype && depth < MAX_ERROR_PROTOTYPE_DEPTH; depth++) {
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
+ if (typeof constructor == "function" && constructor.name === "AggregateError") {
+ const errors = input.errors;
+ return isArray(errors) ? errors : undefined;
}
- };
- return {
- kvlistValue: {
- values: encodeKeyValueList(value, logger, state, depth + 1)
+ prototype = Object.getPrototypeOf(prototype);
}
- };
- } finally {
- state.ancestors.delete(value);
- }
+ }
+ } catch {}
}
- return {
- stringValue: sanitizeString(String(value))
- };
-}
-function encodeArrayValues(values, logger, state, depth) {
- const result = [];
- const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
- let index = 0;
- for (;index < itemCount && state.remainingNodes > 0; index++)
- try {
- const element = index in values ? values[index] : undefined;
- if (isNullish(element))
- continue;
- result.push(encodeAnyValue(element, logger, state, depth));
- } catch {
- result.push({
- stringValue: UNSERIALIZABLE_VALUE
- });
- }
- if (values.length > index)
- result.push({
- stringValue: TRUNCATED_VALUE
- });
- return result;
-}
-function encodeKeyValueList(attrs, logger, state, depth) {
- const result = [];
- for (const key in attrs)
- if (propertyIsEnumerable.call(attrs, key)) {
- if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
- logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
- break;
+ buildCoercingContext(mechanism, hint, depth = 0) {
+ let count = 0;
+ let memberInspections = 0;
+ let hasAggregate = false;
+ const seen = new Set;
+ const wrappers = [];
+ const skipped = {};
+ const coerce = (input, depth, wrapperDepth = 0) => {
+ const ctx = createContext(depth, wrapperDepth);
+ const forward = ctx.apply;
+ ctx.apply = (nextInput) => {
+ wrappers.push(input);
+ try {
+ return forward(nextInput);
+ } finally {
+ wrappers.pop();
+ }
+ };
+ if (wrapperDepth > MAX_WRAPPER_RECURSION || wrapperDepth > 0 && wrappers.indexOf(input) !== -1)
+ return this.coerceFallback(ctx);
+ const isReference = typeof input == "object" && input !== null || typeof input == "function";
+ if (wrapperDepth === 0 && count >= MAX_EXCEPTIONS || isReference && seen.has(input))
+ return;
+ if (isReference)
+ seen.add(input);
+ if (wrapperDepth === 0)
+ count++;
+ const errors = this.getAggregateErrors(input);
+ hasAggregate ||= !!errors;
+ let exception;
+ try {
+ exception = this.applyCoercers(input, ctx);
+ if (!exception)
+ throw skipped;
+ } catch (error) {
+ if (error === skipped) {
+ if (wrapperDepth === 0)
+ count--;
+ return;
+ }
+ if (!hasAggregate)
+ throw error;
+ exception = this.coerceFallback(ctx);
}
+ if (!errors || count >= MAX_EXCEPTIONS)
+ return exception;
+ let length;
try {
- const value = attrs[key];
- if (isNull(value) || isUndefined(value))
- continue;
- result.push({
- key: sanitizeString(key),
- value: encodeAnyValue(value, logger, state, depth)
- });
+ length = errors.length;
} catch {
- result.push({
- key: sanitizeString(key),
- value: {
- stringValue: UNSERIALIZABLE_VALUE
- }
- });
+ return exception;
}
- }
- return result;
-}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
-var DEFAULT_HISTOGRAM_BOUNDS = [
- 0,
- 5,
- 10,
- 25,
- 50,
- 75,
- 100,
- 250,
- 500,
- 750,
- 1000,
- 2500,
- 5000,
- 7500,
- 1e4
-];
-function msToUnixNano(ms) {
- return String(ms) + "000000";
-}
-function seriesKey(type, name, unit, attributes) {
- let attrsKey = "";
- if (attributes) {
- const keys = Object.keys(attributes).sort();
- attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
+ if (!Number.isInteger(length) || length < 0 || length > 4294967295)
+ return exception;
+ const children = [];
+ for (let index = 0;count < MAX_EXCEPTIONS && memberInspections < MAX_AGGREGATE_MEMBER_INSPECTIONS && index < length; index++) {
+ memberInspections++;
+ let child;
+ try {
+ child = ctx.next(errors[index]);
+ } catch {
+ count++;
+ child = this.coerceFallback(createContext(depth + 1));
+ }
+ if (child)
+ children.push(child);
+ }
+ return {
+ ...exception,
+ errors: children
+ };
+ };
+ const createContext = (depth, wrapperDepth = 0) => ({
+ ...hint,
+ syntheticException: depth == 0 ? hint.syntheticException : undefined,
+ mechanism: depth == 0 ? mechanism : {},
+ apply: (input) => {
+ const exception = coerce(input, depth, wrapperDepth + 1);
+ if (!exception)
+ throw skipped;
+ return exception;
+ },
+ next: (input) => coerce(input, depth + 1)
+ });
+ const context = createContext(depth);
+ return {
+ ...context,
+ apply: (input) => coerce(input, depth) ?? this.coerceFallback(context)
+ };
}
- return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
}
-function bucketIndexFor(value, bounds) {
- for (let i = 0;i < bounds.length; i++)
- if (value <= bounds[i])
- return i;
- return bounds.length;
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
+var UNKNOWN_FUNCTION = "?";
+var ANONYMOUS_FILENAME = "<anonymous>";
+var URL_SCHEME = /^([a-z][a-z0-9.+-]+):/i;
+var APP_URL_SCHEMES = [
+ "http",
+ "https",
+ "file",
+ "blob",
+ "app",
+ "capacitor",
+ "ionic",
+ "webpack",
+ "webpack-internal",
+ "ng"
+];
+function isAppFilename(filename) {
+ if (!filename || filename === ANONYMOUS_FILENAME)
+ return false;
+ const scheme = URL_SCHEME.exec(filename);
+ return !scheme || APP_URL_SCHEMES.includes(scheme[1].toLowerCase());
}
-function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
- return {
- ...config.resourceAttributes,
- "service.name": config.serviceName || "unknown_service",
- ...config.environment && {
- "deployment.environment": config.environment
- },
- ...config.serviceVersion && {
- "service.version": config.serviceVersion
- },
- "telemetry.sdk.name": scopeName,
- "telemetry.sdk.version": scopeVersion
- };
-}
-function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
- return {
- resourceMetrics: [
- {
- resource: {
- attributes: toOtlpKeyValueList(resourceAttributes)
- },
- scopeMetrics: [
- {
- scope: {
- name: scopeName,
- version: scopeVersion
- },
- metrics
- }
- ]
- }
- ]
- };
-}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
-var DEFAULT_FLUSH_INTERVAL_MS = 1e4;
-var DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
-function resolveMetricsConfig(config) {
- const resourceAttributes = config?.resourceAttributes;
- return {
- serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
- serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
- environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
- resourceAttributes,
- beforeSend: config?.beforeSend,
- flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
- maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
+function createFrame(platform, filename, func, lineno, colno) {
+ const frame = {
+ platform,
+ filename,
+ function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
+ in_app: isAppFilename(filename)
};
+ if (!isUndefined(lineno))
+ frame.lineno = lineno;
+ if (!isUndefined(colno))
+ frame.colno = colno;
+ return frame;
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
-var OTLP_TEMPORALITY_DELTA = 1;
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
+var extractSafariExtensionDetails = (func, filename) => {
+ const isSafariExtension = func.indexOf("safari-extension") !== -1;
+ const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
+ return isSafariExtension || isSafariWebExtension ? [
+ func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
+ ] : [
+ func,
+ filename
+ ];
+};
-class PostHogMetrics {
- constructor(_instance, _config, _logger) {
- this._instance = _instance;
- this._config = _config;
- this._logger = _logger;
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- this._generation = 0;
- }
- count(name, value = 1, options) {
- this._capture({
- name,
- type: "count",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- gauge(name, value, options) {
- this._capture({
- name,
- type: "gauge",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- histogram(name, value, options) {
- this._capture({
- name,
- type: "histogram",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- flush() {
- const prev = this._flushPromise;
- const run = async () => {
- if (prev)
- await prev.catch(() => {});
- await this._doFlush();
- };
- const p = run().finally(() => {
- if (this._flushPromise === p)
- this._flushPromise = null;
- });
- this._flushPromise = p;
- return p;
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
+var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
+var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
+var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
+var chromeStackLineParser = (line, platform) => {
+ const noFnParts = chromeRegexNoFnName.exec(line);
+ if (noFnParts) {
+ const [, filename, line, col] = noFnParts;
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
}
- drainWindow() {
- if (this._series.size === 0)
- return null;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- return this._buildPayload(window);
+ const parts = chromeRegex.exec(line);
+ if (parts) {
+ const isEval = parts[2] && parts[2].indexOf("eval") === 0;
+ if (isEval) {
+ const subMatch = chromeEvalRegex.exec(parts[2]);
+ if (subMatch) {
+ parts[2] = subMatch[1];
+ parts[3] = subMatch[2];
+ parts[4] = subMatch[3];
+ }
+ }
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
}
- reset() {
- this._generation++;
- this._clearFlushTimer();
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
+};
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
+var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
+var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
+var geckoStackLineParser = (line, platform) => {
+ const parts = geckoREgex.exec(line);
+ if (parts) {
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
+ if (isEval) {
+ const subMatch = geckoEvalRegex.exec(parts[3]);
+ if (subMatch) {
+ parts[1] = parts[1] || "eval";
+ parts[3] = subMatch[1];
+ parts[4] = subMatch[2];
+ parts[5] = "";
+ }
+ }
+ let filename = parts[3];
+ let func = parts[1] || UNKNOWN_FUNCTION;
+ [func, filename] = extractSafariExtensionDetails(func, filename);
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
}
- _capture(sample) {
- if (this._instance.isDisabled || this._instance.optedOut)
- return;
- const filtered = this._runBeforeSend(sample);
- if (filtered === null)
- return;
- if (!filtered.name || typeof filtered.name != "string")
- return void this._logger.warn("Dropping metric with empty name");
- if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
- return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
- if (filtered.type === "count" && filtered.value < 0)
- return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
- let attributes;
- let key;
- try {
- attributes = filtered.attributes ? {
- ...filtered.attributes
- } : undefined;
- key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
- } catch (e) {
- this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
- return;
+};
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
+var FILENAME_MATCH = /^\s*[-]{4,}$/;
+var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
+var PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
+var PROMISE_INDEX = /^index \d+$/;
+var PROMISE_FRAME_FILENAME = "node:internal/promise";
+var nodeStackLineParser = (line, platform) => {
+ const lineMatch = line.match(FULL_MATCH);
+ if (lineMatch) {
+ let object;
+ let method;
+ let functionName;
+ let typeName;
+ let methodName;
+ if (lineMatch[1]) {
+ functionName = lineMatch[1];
+ let methodStart = functionName.lastIndexOf(".");
+ if (functionName[methodStart - 1] === ".")
+ methodStart--;
+ if (methodStart > 0) {
+ object = functionName.slice(0, methodStart);
+ method = functionName.slice(methodStart + 1);
+ const objectEnd = object.indexOf(".Module");
+ if (objectEnd > 0) {
+ functionName = functionName.slice(objectEnd + 1);
+ object = object.slice(0, objectEnd);
+ }
+ }
+ typeName = undefined;
}
- let state = this._series.get(key);
- if (!state) {
- if (!this._admitNewSeries())
- return;
- state = {
- name: filtered.name,
- type: filtered.type,
- unit: filtered.unit,
- attributes,
- windowStartMs: Date.now()
- };
- this._series.set(key, state);
+ if (method) {
+ typeName = object;
+ methodName = method;
}
- const seenType = this._typeByName.get(filtered.name);
- if (seenType === undefined)
- this._typeByName.set(filtered.name, filtered.type);
- else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
- this._typeCollisionWarned.add(filtered.name);
- this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
+ if (method === "<anonymous>") {
+ methodName = undefined;
+ functionName = undefined;
}
- this._fold(state, filtered.value);
- this._armFlushTimer();
- }
- _admitNewSeries() {
- if (this._series.size < this._config.maxSeriesPerFlush)
- return true;
- if (!this._seriesCapWarned) {
- this._seriesCapWarned = true;
- this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
+ if (functionName === undefined) {
+ methodName = methodName || UNKNOWN_FUNCTION;
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
}
- return false;
- }
- _fold(state, value) {
- switch (state.type) {
- case "count":
- state.total = (state.total ?? 0) + value;
- break;
- case "gauge":
- state.last = value;
- break;
- case "histogram": {
- if (!state.hist)
- state.hist = {
- count: 0,
- sum: 0,
- min: value,
- max: value,
- bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
- };
- const hist = state.hist;
- hist.count += 1;
- hist.sum += value;
- hist.min = Math.min(hist.min, value);
- hist.max = Math.max(hist.max, value);
- hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
+ let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
+ const isNative = lineMatch[5] === "native";
+ if (filename?.match(/\/[A-Z]:/))
+ filename = filename.slice(1);
+ if (!filename && lineMatch[5] && !isNative)
+ filename = lineMatch[5];
+ if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
+ filename = PROMISE_FRAME_FILENAME;
+ return {
+ filename: filename ? decodeURI(filename) : undefined,
+ module: undefined,
+ function: functionName,
+ lineno: _parseIntOrUndefined(lineMatch[3]),
+ colno: _parseIntOrUndefined(lineMatch[4]),
+ in_app: filenameIsInApp(filename || "", isNative),
+ platform
+ };
+ }
+ if (line.match(FILENAME_MATCH))
+ return {
+ filename: line,
+ platform
+ };
+};
+function filenameIsInApp(filename, isNative = false) {
+ const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
+ return !isInternal && filename !== undefined && !filename.includes("node_modules/");
+}
+function _parseIntOrUndefined(input) {
+ return parseInt(input || "", 10) || undefined;
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
+var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
+var STACKTRACE_FRAME_LIMIT = 50;
+var MAX_REPEATED_CYCLE_LENGTH = 10;
+var STACKTRACE_LINE_LIMIT = 1000;
+function isSameFrame(a, b) {
+ return a.filename === b.filename && a.function === b.function && a.module === b.module && a.lineno === b.lineno && a.colno === b.colno;
+}
+function collapseRepeatedCycle(frames) {
+ for (let length = 1;length <= MAX_REPEATED_CYCLE_LENGTH; length++) {
+ const start = frames.length - 2 * length;
+ if (start < 0)
+ break;
+ let isCycle = true;
+ for (let offset = 0;offset < length; offset++) {
+ const inner = frames[start + offset];
+ if (!isSameFrame(inner, frames[start + length + offset])) {
+ isCycle = false;
break;
}
}
+ if (isCycle) {
+ for (let offset = 0;offset < length; offset++)
+ frames[start + offset] = frames[start + length + offset];
+ frames.length = start + length;
+ return {
+ start,
+ length
+ };
+ }
}
- _runBeforeSend(sample) {
- const beforeSend = this._config.beforeSend;
- if (!beforeSend)
- return sample;
- const fns = isArray(beforeSend) ? beforeSend : [
- beforeSend
- ];
- let result = sample;
- for (const fn of fns)
- try {
- const next = fn(result);
- if (!next) {
- this._logger.info("Metric was rejected in beforeSend function");
- return null;
+}
+function trimPartialCycle(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ const partialLength = partialCycleLength(frames, cycle);
+ if (partialLength)
+ frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength);
+}
+function innermostPartialCycleLength(frames, cycle) {
+ let partialStart = cycle.start;
+ while (partialStart > 0 && isSameFrame(frames[partialStart - 1], frames[partialStart - 1 + cycle.length]))
+ partialStart--;
+ return cycle.start - partialStart;
+}
+function partialCycleLength(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ let partialEnd = copyEnd;
+ while (partialEnd < frames.length && isSameFrame(frames[partialEnd], frames[partialEnd - cycle.length]))
+ partialEnd++;
+ return partialEnd - copyEnd;
+}
+function survivingFrameCount(frames, cycles) {
+ const innermostCycle = cycles[0];
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0);
+ for (const cycle of cycles)
+ count -= partialCycleLength(frames, cycle);
+ return count;
+}
+function canonicalizeCycleRotation(frames) {
+ const keys = frames.map((frame) => `${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`);
+ let first = 0;
+ for (let i = 1;i < keys.length; i++)
+ if (isSmallerRotation(keys, i, first))
+ first = i;
+ frames.push(...frames.splice(0, first));
+}
+function isSmallerRotation(keys, candidate, best) {
+ for (let offset = 0;offset < keys.length; offset++) {
+ const left = keys[(candidate + offset) % keys.length];
+ const right = keys[(best + offset) % keys.length];
+ if (left !== right)
+ return left < right;
+ }
+ return false;
+}
+function reverseAndStripFrames(stack) {
+ if (!stack.length)
+ return [];
+ const localStack = Array.from(stack);
+ localStack.reverse();
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
+ ...frame,
+ filename: frame.filename || getLastStackFrame(localStack).filename,
+ function: frame.function || UNKNOWN_FUNCTION
+ }));
+}
+function getLastStackFrame(arr) {
+ return arr[arr.length - 1] || {};
+}
+function createDefaultStackParser() {
+ return createStackParser("web:javascript", chromeStackLineParser, geckoStackLineParser);
+}
+function createStackParser(platform, ...parsers) {
+ return (stack, skipFirstLines = 0) => {
+ const frames = [];
+ const lines = stack.split(`
+`);
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT);
+ const repeatedCycles = [];
+ for (let i = skipFirstLines;i < endLine; i++) {
+ const line = lines[i];
+ if (line.length > 1024)
+ continue;
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
+ if (!cleanedLine.match(/\S*Error: /)) {
+ for (const parser of parsers) {
+ const frame = parser(cleanedLine, platform);
+ if (frame) {
+ frames.push(frame);
+ const cycle = collapseRepeatedCycle(frames);
+ if (cycle) {
+ for (let i = repeatedCycles.length - 1;i >= 0; i--) {
+ const previous = repeatedCycles[i];
+ if (previous.start + previous.length <= cycle.start)
+ break;
+ repeatedCycles.pop();
+ }
+ repeatedCycles.push(cycle);
+ }
+ break;
+ }
}
- result = next;
- } catch (e) {
- this._logger.error("Error in beforeSend function for metric:", e);
- return null;
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT)
+ break;
}
- return result;
+ }
+ const sections = [
+ ...repeatedCycles
+ ].sort((a, b) => b.start - a.start);
+ const innermostSection = sections[sections.length - 1];
+ if (innermostSection) {
+ const trimmed = innermostPartialCycleLength(frames, innermostSection);
+ frames.splice(innermostSection.start - trimmed, trimmed);
+ for (const cycle of sections)
+ cycle.start -= trimmed;
+ }
+ for (const cycle of sections)
+ trimPartialCycle(frames, cycle);
+ if (repeatedCycles.some((cycle) => cycle.start === 0 && frames.length === cycle.length))
+ canonicalizeCycleRotation(frames);
+ return reverseAndStripFrames(frames);
+ };
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
+class ErrorCoercer {
+ match(err) {
+ return isError(err);
}
- _armFlushTimer() {
- if (this._flushTimer)
- return;
- this._flushTimer = safeSetTimeout(() => {
- this._flushTimer = undefined;
- this.flush().catch((e) => {
- this._logger.error("Metrics flush failed:", e);
- });
- }, this._config.flushIntervalMs);
+ coerce(err, ctx) {
+ const stack = this.getStack(err);
+ const replacementStack = stack === undefined ? ctx.syntheticException?.stack : undefined;
+ const synthetic = !!replacementStack;
+ return {
+ type: this.getType(err),
+ value: this.getMessage(err, ctx),
+ stack: stack ?? replacementStack,
+ cause: err.cause ? ctx.next(err.cause) : undefined,
+ synthetic
+ };
}
- _clearFlushTimer() {
- if (this._flushTimer) {
- clearTimeout(this._flushTimer);
- this._flushTimer = undefined;
- }
+ getType(err) {
+ return err.name || err.constructor.name;
}
- async _doFlush() {
- if (this._series.size === 0)
- return;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- const generation = this._generation;
- const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
- if (generation !== this._generation)
+ getMessage(err, _ctx) {
+ const message = err.message;
+ if (message.error && typeof message.error.message == "string")
+ return String(message.error.message);
+ return String(message);
+ }
+ getStack(err) {
+ try {
+ const stacktrace = err.stacktrace;
+ if (typeof stacktrace == "string" && stacktrace.length > 0)
+ return stacktrace;
+ const stack = err.stack;
+ return typeof stack == "string" && stack.length > 0 ? stack : undefined;
+ } catch {
return;
- switch (outcome.kind) {
- case "ok":
- return;
- case "retry-later":
- this._mergeWindowBack(window);
- this._armFlushTimer();
- return;
- case "too-large":
- this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
- return;
- case "fatal":
- this._logger.error("Failed to send metrics batch:", outcome.error);
- return;
}
}
- _buildPayload(window) {
- return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
+var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
+
+class StringCoercer {
+ match(input) {
+ return typeof input == "string";
}
- _buildMetrics(window) {
- const nowNano = msToUnixNano(Date.now());
- const byMetric = new Map;
- for (const state of window.values()) {
- const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
- let metric = byMetric.get(metricKey);
- if (!metric) {
- metric = {
- name: state.name,
- ...state.unit && {
- unit: state.unit
- }
- };
- if (state.type === "count")
- metric.sum = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- isMonotonic: true,
- dataPoints: []
- };
- else if (state.type === "gauge")
- metric.gauge = {
- dataPoints: []
- };
- else
- metric.histogram = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- dataPoints: []
- };
- byMetric.set(metricKey, metric);
- }
- const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
- const startNano = msToUnixNano(state.windowStartMs);
- if (state.type === "count") {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- asDouble: state.total ?? 0
- };
- metric.sum.dataPoints.push(dp);
- } else if (state.type === "gauge") {
- const dp = {
- attributes,
- timeUnixNano: nowNano,
- asDouble: state.last ?? 0
- };
- metric.gauge.dataPoints.push(dp);
- } else if (state.hist) {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- count: state.hist.count,
- sum: state.hist.sum,
- min: state.hist.min,
- max: state.hist.max,
- bucketCounts: state.hist.bucketCounts,
- explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
- };
- metric.histogram.dataPoints.push(dp);
- }
+ coerce(input, ctx) {
+ const [type, value] = this.getInfos(input);
+ return {
+ type: type ?? "Error",
+ value: value ?? input,
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
+ };
+ }
+ getInfos(candidate) {
+ let type = "Error";
+ let value = candidate;
+ const groups = candidate.match(ERROR_TYPES_PATTERN);
+ if (groups) {
+ type = groups[1];
+ value = groups[2];
}
- return Array.from(byMetric.values());
+ return [
+ type,
+ value
+ ];
}
- _mergeWindowBack(window) {
- for (const [key, old] of window) {
- const current = this._series.get(key);
- if (!current) {
- if (this._admitNewSeries())
- this._series.set(key, old);
- continue;
- }
- current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
- switch (current.type) {
- case "count":
- current.total = (current.total ?? 0) + (old.total ?? 0);
- break;
- case "gauge":
- break;
- case "histogram":
- if (old.hist)
- if (current.hist) {
- current.hist.count += old.hist.count;
- current.hist.sum += old.hist.sum;
- current.hist.min = Math.min(current.hist.min, old.hist.min);
- current.hist.max = Math.max(current.hist.max, old.hist.max);
- for (let i = 0;i < current.hist.bucketCounts.length; i++)
- current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
- } else
- current.hist = old.hist;
- break;
- }
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
+var severityLevels = [
+ "fatal",
+ "error",
+ "warning",
+ "log",
+ "info",
+ "debug"
+];
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
+function extractExceptionKeysForMessage(err, maxLength = 40) {
+ const keys = Object.keys(err);
+ keys.sort();
+ if (!keys.length)
+ return "[object has no keys]";
+ for (let i = keys.length;i > 0; i--) {
+ const serialized = keys.slice(0, i).join(", ");
+ if (!(serialized.length > maxLength)) {
+ if (i === keys.length)
+ return serialized;
+ return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
}
}
+ return "";
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
-class SimpleEventEmitter {
- constructor() {
- this.events = {};
- this.events = {};
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
+class ObjectCoercer {
+ match(candidate) {
+ return typeof candidate == "object" && candidate !== null;
}
- on(event, listener) {
- if (!this.events[event])
- this.events[event] = [];
- this.events[event].push(listener);
- return () => {
- this.events[event] = this.events[event].filter((x) => x !== listener);
+ coerce(candidate, ctx) {
+ const errorProperty = this.getErrorPropertyFromObject(candidate);
+ if (errorProperty)
+ return ctx.apply(errorProperty);
+ return {
+ type: this.getType(candidate),
+ value: this.getValue(candidate),
+ stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
+ level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
+ synthetic: true
};
}
- emit(event, payload) {
- for (const listener of this.events[event] || [])
- listener(payload);
- for (const listener of this.events["*"] || [])
- listener(event, payload);
+ getType(err) {
+ if (isEvent(err))
+ return err.constructor.name;
+ const name = "name" in err ? err.name : undefined;
+ return isString(name) && !isEmptyString(name) ? name : "Error";
}
-}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
-var parsedStackResults;
-var lastKeysCount;
-var cachedFilenameChunkIds;
-function getFilenameToChunkIdMap(stackParser) {
- const chunkIdMap = globalThis._posthogChunkIds;
- if (!chunkIdMap)
- return;
- const chunkIdKeys = Object.keys(chunkIdMap);
- if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
- return cachedFilenameChunkIds;
- lastKeysCount = chunkIdKeys.length;
- cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
- if (!parsedStackResults)
- parsedStackResults = {};
- const result = parsedStackResults[stackKey];
- if (result)
- acc[result[0]] = result[1];
- else {
- const parsedStack = stackParser(stackKey);
- for (let i = parsedStack.length - 1;i >= 0; i--) {
- const stackFrame = parsedStack[i];
- const filename = stackFrame?.filename;
- const chunkId = chunkIdMap[stackKey];
- if (filename && chunkId) {
- acc[filename] = chunkId;
- parsedStackResults[stackKey] = [
- filename,
- chunkId
- ];
- break;
- }
+ getValue(err) {
+ if ("name" in err && typeof err.name == "string") {
+ let message = `'${err.name}' captured as exception`;
+ if ("message" in err && typeof err.message == "string")
+ message += ` with message: '${err.message}'`;
+ return message;
+ }
+ if ("message" in err && typeof err.message == "string")
+ return err.message;
+ const className = this.getObjectClassName(err);
+ const keys = extractExceptionKeysForMessage(err);
+ return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
+ }
+ isSeverityLevel(x) {
+ return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
+ }
+ getStack(candidate) {
+ try {
+ if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
+ return candidate.stacktrace;
+ return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
+ } catch {
+ return;
+ }
+ }
+ getErrorPropertyFromObject(obj) {
+ for (const prop in obj)
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
+ const value = obj[prop];
+ if (isError(value))
+ return value;
}
+ }
+ getObjectClassName(obj) {
+ try {
+ const prototype = Object.getPrototypeOf(obj);
+ return prototype ? prototype.constructor.name : undefined;
+ } catch (e) {
+ return;
}
- return acc;
- }, {});
- return cachedFilenameChunkIds;
+ }
}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
-var MAX_CAUSE_RECURSION = 4;
-
-class ErrorPropertiesBuilder {
- constructor(coercers, stackParser, modifiers = []) {
- this.coercers = coercers;
- this.stackParser = stackParser;
- this.modifiers = modifiers;
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
+class EventCoercer {
+ match(err) {
+ return isEvent(err);
}
- buildFromUnknown(input, hint = {}) {
- const providedMechanism = hint && hint.mechanism;
- const mechanism = providedMechanism || {
- handled: true,
- type: "generic"
- };
- const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
- const exceptionWithCause = coercingContext.apply(input);
- const parsingContext = this.buildParsingContext(hint);
- const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
- const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
+ coerce(evt, ctx) {
+ const constructorName = evt.constructor.name;
return {
- $exception_list: exceptionList,
- $exception_level: "error"
+ type: constructorName,
+ value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
};
}
- async modifyFrames(exceptionList) {
- for (const exc of exceptionList)
- if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
- exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
- return exceptionList;
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
+class PrimitiveCoercer {
+ match(candidate) {
+ return isPrimitive(candidate);
}
- coerceFallback(ctx) {
+ coerce(value, ctx) {
return {
type: "Error",
- value: "Unknown error",
+ value: `Primitive value captured as exception: ${String(value)}`,
stack: ctx.syntheticException?.stack,
synthetic: true
};
}
- parseStacktrace(err, ctx) {
- let cause;
- if (err.cause != null)
- cause = this.parseStacktrace(err.cause, ctx);
- let stack;
- if (err.stack != "" && err.stack != null)
- stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
- return {
- ...err,
- cause,
- stack
- };
- }
- applyChunkIds(frames, chunkIdMap) {
- return frames.map((frame) => {
- if (frame.filename && chunkIdMap)
- frame.chunk_id = chunkIdMap[frame.filename];
- return frame;
- });
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
+class ReduceableCache {
+ constructor(_maxSize) {
+ this._maxSize = _maxSize;
+ this._cache = new Map;
}
- applyCoercers(input, ctx) {
- for (const adapter of this.coercers)
- if (adapter.match(input))
- return adapter.coerce(input, ctx);
- return this.coerceFallback(ctx);
+ get(key) {
+ const value = this._cache.get(key);
+ if (value === undefined)
+ return;
+ this._cache.delete(key);
+ this._cache.set(key, value);
+ return value;
}
- async applyModifiers(frames) {
- let newFrames = frames;
- for (const modifier of this.modifiers)
- newFrames = await modifier(newFrames);
- return newFrames;
+ set(key, value) {
+ this._cache.set(key, value);
}
- convertToExceptionList(exceptionWithStack, mechanism) {
- const currentException = {
- type: exceptionWithStack.type,
- value: exceptionWithStack.value,
- mechanism: {
- type: mechanism.type ?? "generic",
- handled: mechanism.handled ?? true,
- synthetic: exceptionWithStack.synthetic ?? false
- }
- };
- if (exceptionWithStack.stack)
- currentException.stacktrace = {
- type: "raw",
- frames: exceptionWithStack.stack
- };
- const exceptionList = [
- currentException
- ];
- if (exceptionWithStack.cause != null)
- exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
- ...mechanism,
- handled: true
- }));
- return exceptionList;
+ reduce() {
+ while (this._cache.size >= this._maxSize) {
+ const value = this._cache.keys().next().value;
+ if (value)
+ this._cache.delete(value);
+ }
}
- buildParsingContext(hint) {
- const context = {
- chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
- skipFirstLines: hint.skipFirstLines ?? 1
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
+var EXCEPTION_STEP_INTERNAL_FIELDS = {
+ MESSAGE: "$message",
+ TIMESTAMP: "$timestamp"
+};
+var RESERVED_EXCEPTION_STEP_KEYS = new Set([
+ EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
+ EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
+]);
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
+function getInjectedReleaseId() {
+ const injected = globalThis._posthogReleaseId;
+ return typeof injected == "string" && injected.length > 0 ? injected : undefined;
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
+var normalizeFlagsResponse = (flagsResponse) => {
+ if ("flags" in flagsResponse) {
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads
};
- return context;
}
- buildCoercingContext(mechanism, hint, depth = 0) {
- const coerce = (input, depth) => {
- if (!(depth <= MAX_CAUSE_RECURSION))
- return;
- {
- const ctx = this.buildCoercingContext(mechanism, hint, depth);
- return this.applyCoercers(input, ctx);
- }
- };
- const context = {
- ...hint,
- syntheticException: depth == 0 ? hint.syntheticException : undefined,
- mechanism,
- apply: (input) => coerce(input, depth),
- next: (input) => coerce(input, depth + 1)
+ {
+ const featureFlags = flagsResponse.featureFlags ?? {};
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
+ k,
+ parsePayload(v)
+ ]));
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
+ key,
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
+ ]));
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads,
+ flags
};
- return context;
}
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
-var UNKNOWN_FUNCTION = "?";
-var MASKED_URL_PREFIX = "webkit-masked-url://";
-var ANONYMOUS_FILENAME = "<anonymous>";
-function createFrame(platform, filename, func, lineno, colno) {
- const frame = {
- platform,
- filename,
- function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
- in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
+};
+function getFlagDetailFromFlagAndPayload(key, value, payload) {
+ return {
+ key,
+ enabled: typeof value == "string" ? true : value,
+ variant: typeof value == "string" ? value : undefined,
+ reason: undefined,
+ metadata: {
+ id: undefined,
+ version: undefined,
+ payload: payload ? JSON.stringify(payload) : undefined,
+ description: undefined
+ }
};
- if (!isUndefined(lineno))
- frame.lineno = lineno;
- if (!isUndefined(colno))
- frame.colno = colno;
- return frame;
}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
-var extractSafariExtensionDetails = (func, filename) => {
- const isSafariExtension = func.indexOf("safari-extension") !== -1;
- const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
- return isSafariExtension || isSafariWebExtension ? [
- func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
- isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
- ] : [
- func,
- filename
- ];
+var getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
+ key,
+ getFeatureFlagValue(detail)
+]).filter(([, value]) => value !== undefined));
+var getPayloadsFromFlags = (flags) => {
+ const safeFlags = flags ?? {};
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
+ const details = safeFlags[flag];
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
+ }).map((flag) => {
+ const payload = safeFlags[flag].metadata?.payload;
+ return [
+ flag,
+ payload ? parsePayload(payload) : undefined
+ ];
+ }));
+};
+var getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled;
+var parsePayload = (response) => {
+ if (typeof response != "string")
+ return response;
+ try {
+ return JSON.parse(response);
+ } catch {
+ return response;
+ }
+};
+var MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_content",
+ "utm_term",
+ "gad_source",
+ "mc_cid",
+ "gclid",
+ "gclsrc",
+ "dclid",
+ "gbraid",
+ "wbraid",
+ "fbclid",
+ "msclkid",
+ "twclid",
+ "li_fat_id",
+ "igshid",
+ "ttclid",
+ "rdt_cid",
+ "epik",
+ "qclid",
+ "sccid",
+ "irclid",
+ "_kx"
+];
+var MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
+ "$feature_flag",
+ "$feature_flag_response",
+ "$feature_flag_has_experiment",
+ "$feature_flag_id",
+ "$feature_flag_version",
+ "$feature_flag_reason",
+ "$feature_flag_request_id",
+ "$feature_flag_evaluated_at",
+ "$feature_flag_error",
+ "locally_evaluated",
+ "$groups",
+ "$process_person_profile",
+ "$geoip_disable",
+ "$current_url",
+ "$pathname",
+ "$referring_domain",
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
+ "$session_id",
+ "$window_id",
+ "$lib",
+ "$lib_version",
+ "$device_id",
+ "$is_server"
+];
+var minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
+ const minimal = {};
+ const copyKey = (key) => {
+ if (properties[key] !== undefined)
+ minimal[key] = properties[key];
+ };
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
+ transportKeys.forEach(copyKey);
+ return minimal;
};
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
-var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
-var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
-var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
-var chromeStackLineParser = (line, platform) => {
- const noFnParts = chromeRegexNoFnName.exec(line);
- if (noFnParts) {
- const [, filename, line, col] = noFnParts;
- return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
+class SimpleEventEmitter {
+ constructor() {
+ this.events = {};
+ this.events = {};
}
- const parts = chromeRegex.exec(line);
- if (parts) {
- const isEval = parts[2] && parts[2].indexOf("eval") === 0;
- if (isEval) {
- const subMatch = chromeEvalRegex.exec(parts[2]);
- if (subMatch) {
- parts[2] = subMatch[1];
- parts[3] = subMatch[2];
- parts[4] = subMatch[3];
- }
- }
- const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
- return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
+ on(event, listener) {
+ if (!this.events[event])
+ this.events[event] = [];
+ this.events[event].push(listener);
+ return () => {
+ this.events[event] = this.events[event].filter((x) => x !== listener);
+ };
}
-};
+ emit(event, payload) {
+ for (const listener of this.events[event] || [])
+ listener(payload);
+ for (const listener of this.events["*"] || [])
+ listener(event, payload);
+ }
+}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
-var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
-var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
-var geckoStackLineParser = (line, platform) => {
- const parts = geckoREgex.exec(line);
- if (parts) {
- const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
- if (isEval) {
- const subMatch = geckoEvalRegex.exec(parts[3]);
- if (subMatch) {
- parts[1] = parts[1] || "eval";
- parts[3] = subMatch[1];
- parts[4] = subMatch[2];
- parts[5] = "";
- }
- }
- let filename = parts[3];
- let func = parts[1] || UNKNOWN_FUNCTION;
- [func, filename] = extractSafariExtensionDetails(func, filename);
- return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
+function isGzipSupported() {
+ return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+}
+var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError";
+var GZIP_MAGIC_FIRST_BYTE = 31;
+var GZIP_MAGIC_SECOND_BYTE = 139;
+var GZIP_DEFLATE_METHOD = 8;
+var hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;
+var crc32Table;
+var getCrc32Table = () => {
+ if (crc32Table)
+ return crc32Table;
+ crc32Table = [];
+ for (let i = 0;i < 256; i++) {
+ let crc = i;
+ for (let j = 0;j < 8; j++)
+ crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
+ crc32Table[i] = crc >>> 0;
}
+ return crc32Table;
};
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
-var FILENAME_MATCH = /^\s*[-]{4,}$/;
-var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
-var PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
-var PROMISE_INDEX = /^index \d+$/;
-var PROMISE_FRAME_FILENAME = "node:internal/promise";
-var nodeStackLineParser = (line, platform) => {
- const lineMatch = line.match(FULL_MATCH);
- if (lineMatch) {
- let object;
- let method;
- let functionName;
- let typeName;
- let methodName;
- if (lineMatch[1]) {
- functionName = lineMatch[1];
- let methodStart = functionName.lastIndexOf(".");
- if (functionName[methodStart - 1] === ".")
- methodStart--;
- if (methodStart > 0) {
- object = functionName.slice(0, methodStart);
- method = functionName.slice(methodStart + 1);
- const objectEnd = object.indexOf(".Module");
- if (objectEnd > 0) {
- functionName = functionName.slice(objectEnd + 1);
- object = object.slice(0, objectEnd);
+var crc32 = (bytes) => {
+ const table = getCrc32Table();
+ let crc = 4294967295;
+ for (let i = 0;i < bytes.length; i++)
+ crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
+ return (4294967295 ^ crc) >>> 0;
+};
+var throwNativeGzipValidationError = (reason) => {
+ throw createNamedError(NATIVE_GZIP_VALIDATION_ERROR, `Native gzip produced invalid output: ${reason}`);
+};
+var validateNativeGzip = async (compressed, inputBytes) => {
+ if (compressed.size < 18)
+ throwNativeGzipValidationError("too-short");
+ const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
+ if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
+ throwNativeGzipValidationError("invalid-header");
+ const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
+ if (trailer.getUint32(0, true) !== crc32(inputBytes))
+ throwNativeGzipValidationError("invalid-crc");
+ const inputSize = inputBytes.length >>> 0;
+ if (trailer.getUint32(4, true) !== inputSize)
+ throwNativeGzipValidationError("invalid-size");
+};
+async function gzipCompress(input, isDebug = true, options) {
+ try {
+ const inputBytes = new TextEncoder().encode(input);
+ const compressedStream = new globalThis.CompressionStream("gzip");
+ const writer = compressedStream.writable.getWriter();
+ const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
+ try {
+ await writer.abort(err);
+ } catch {}
+ throw err;
+ });
+ const responsePromise = new Response(compressedStream.readable).blob();
+ const [compressed] = await Promise.all([
+ responsePromise,
+ writePromise
+ ]);
+ await validateNativeGzip(compressed, inputBytes);
+ return compressed;
+ } catch (error) {
+ if (options?.rethrow)
+ throw error;
+ if (isDebug)
+ console.error("Failed to gzip compress data", error);
+ return null;
+ }
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
+class PostHogFetchHttpError extends Error {
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
+ }
+ get status() {
+ return this.response.status;
+ }
+ get retryAfterMs() {
+ try {
+ return parseRetryAfterMs(this.response.headers?.get("retry-after"));
+ } catch {
+ return;
+ }
+ }
+ get bodyReadTimedOut() {
+ return this._bodyReadTimedOut;
+ }
+ get text() {
+ if (!this.responseBodyTextPromise)
+ if (Date.now() >= this.responseBodyDeadline) {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ this.cancelResponseBody(timeoutError);
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
+ } else {
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
+ this.responseBodyTimer = safeSetTimeout(() => {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ reject(timeoutError);
+ this.cancelResponseBody(timeoutError);
+ }, this.responseBodyDeadline - Date.now());
+ });
+ let responseBodyText;
+ try {
+ responseBodyText = Promise.resolve(this.response.text());
+ } catch (error) {
+ responseBodyText = Promise.reject(error);
}
+ this.responseBodyTextPromise = Promise.race([
+ responseBodyText,
+ responseBodyTimeout
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
}
- typeName = undefined;
- }
- if (method) {
- typeName = object;
- methodName = method;
- }
- if (method === "<anonymous>") {
- methodName = undefined;
- functionName = undefined;
- }
- if (functionName === undefined) {
- methodName = methodName || UNKNOWN_FUNCTION;
- functionName = typeName ? `${typeName}.${methodName}` : methodName;
- }
- let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
- const isNative = lineMatch[5] === "native";
- if (filename?.match(/\/[A-Z]:/))
- filename = filename.slice(1);
- if (!filename && lineMatch[5] && !isNative)
- filename = lineMatch[5];
- if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
- filename = PROMISE_FRAME_FILENAME;
- return {
- filename: filename ? decodeURI(filename) : undefined,
- module: undefined,
- function: functionName,
- lineno: _parseIntOrUndefined(lineMatch[3]),
- colno: _parseIntOrUndefined(lineMatch[4]),
- in_app: filenameIsInApp(filename || "", isNative),
- platform
- };
+ return this.responseBodyTextPromise;
}
- if (line.match(FILENAME_MATCH))
- return {
- filename: line,
- platform
- };
+ get json() {
+ return this.text.then((text) => JSON.parse(text));
+ }
+ cancelResponseBody(reason) {
+ clearTimeout(this.responseBodyTimer);
+ if (!this.abortController.signal.aborted)
+ this.abortController.abort(reason);
+ (async () => {
+ try {
+ await this.response.body?.cancel();
+ } catch {}
+ })();
+ }
+}
+
+class PostHogFetchNetworkError extends Error {
+ constructor(error) {
+ super("Network error while fetching PostHog", error instanceof Error ? {
+ cause: error
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+ }
+}
+var applyCallerFeatureFlagOverrides = (target, callerProperties) => {
+ for (const key of Object.keys(callerProperties))
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
+ target[key] = callerProperties[key];
};
-function filenameIsInApp(filename, isNative = false) {
- const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
- return !isInternal && filename !== undefined && !filename.includes("node_modules/");
+async function logFlushError(err) {
+ if (err instanceof PostHogFetchHttpError) {
+ let text = "";
+ try {
+ text = await err.text;
+ } catch {
+ if (err.bodyReadTimedOut)
+ text = "<response body read timed out>";
+ }
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
+ } else
+ console.error("Error while flushing PostHog", err);
+ return Promise.resolve();
}
-function _parseIntOrUndefined(input) {
- return parseInt(input || "", 10) || undefined;
+function isPostHogFetchError(err) {
+ return typeof err == "object" && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));
}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
-var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
-var STACKTRACE_FRAME_LIMIT = 50;
-function reverseAndStripFrames(stack) {
- if (!stack.length)
- return [];
- const localStack = Array.from(stack);
- localStack.reverse();
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
- ...frame,
- filename: frame.filename || getLastStackFrame(localStack).filename,
- function: frame.function || UNKNOWN_FUNCTION
- }));
+function isPostHogFetchNetworkError(err) {
+ return err instanceof PostHogFetchNetworkError;
}
-function getLastStackFrame(arr) {
- return arr[arr.length - 1] || {};
+function isRetryableFlagsFetchError(err) {
+ if (err instanceof PostHogFetchHttpError)
+ return err.status === 502 || err.status === 504;
+ if (!(err instanceof PostHogFetchNetworkError))
+ return false;
+ const cause = err.error;
+ const code = cause?.code ?? cause?.cause?.code;
+ return code !== "ECONNREFUSED";
}
-function createDefaultStackParser() {
- return createStackParser("web:javascript", chromeStackLineParser, geckoStackLineParser);
+var OTLP_MAX_BODY_BYTES = 10485760;
+function byteLengthOf(body) {
+ try {
+ if (typeof body != "string")
+ return body instanceof Uint8Array ? body.byteLength : body.size;
+ if ("u" > typeof Buffer)
+ return Buffer.byteLength(body, STRING_FORMAT);
+ return new TextEncoder().encode(body).length;
+ } catch {
+ return 0;
+ }
}
-function createStackParser(platform, ...parsers) {
- return (stack, skipFirstLines = 0) => {
- const frames = [];
- const lines = stack.split(`
-`);
- for (let i = skipFirstLines;i < lines.length; i++) {
- const line = lines[i];
- if (line.length > 1024)
- continue;
- const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
- if (!cleanedLine.match(/\S*Error: /)) {
- for (const parser of parsers) {
- const frame = parser(cleanedLine, platform);
- if (frame) {
- frames.push(frame);
+function isPostHogFetchContentTooLargeError(err) {
+ return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
+}
+function isPostHogFetchRetryableError(err) {
+ if (err instanceof PostHogFetchHttpError)
+ return err.status === 408 || err.status === 429 || err.status >= 500;
+ return isPostHogFetchNetworkError(err);
+}
+function isPostHogEventProperties(value) {
+ return value !== null && typeof value == "object" && !Array.isArray(value);
+}
+var DEFAULT_QUEUE_ROUTE = "default";
+
+class PostHogCoreStateless {
+ getErrorPropertiesBuilder() {
+ if (!this._errorPropertiesBuilder)
+ this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();
+ return this._errorPropertiesBuilder;
+ }
+ createErrorPropertiesBuilder() {
+ return new ErrorPropertiesBuilder([
+ new ErrorCoercer,
+ new ObjectCoercer,
+ new StringCoercer,
+ new PrimitiveCoercer
+ ], createDefaultStackParser());
+ }
+ getEvaluationRuntime() {}
+ constructor(apiKey, options = {}) {
+ this.flushPromise = null;
+ this.pendingFlushPromise = null;
+ this.flushPromises = new Set;
+ this._dequeuedMessagesCount = 0;
+ this.shutdownPromise = null;
+ this.promiseQueue = new PromiseQueue;
+ this._events = new SimpleEventEmitter;
+ this._isInitialized = false;
+ const normalizedApiKey = typeof apiKey == "string" ? apiKey.trim() : "";
+ const normalizedHost = typeof options.host == "string" ? options.host.trim() : "";
+ const missingApiKey = !normalizedApiKey;
+ this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
+ if (missingApiKey)
+ this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");
+ this.apiKey = normalizedApiKey;
+ this.host = removeTrailingSlash(normalizedHost || "https://us.i.posthog.com");
+ this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
+ this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
+ this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);
+ this.flushInterval = options.flushInterval ?? 1e4;
+ this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
+ this.defaultOptIn = options.defaultOptIn ?? true;
+ this.disableSurveys = options.disableSurveys ?? false;
+ this._retryOptions = {
+ retryCount: options.fetchRetryCount ?? 3,
+ retryDelay: options.fetchRetryDelay ?? 3000,
+ retryCheck: isPostHogFetchRetryableError
+ };
+ this.requestTimeout = options.requestTimeout ?? 1e4;
+ this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
+ this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
+ this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
+ this.disableGeoip = options.disableGeoip ?? true;
+ this.disabled = (options.disabled ?? false) || missingApiKey;
+ this.historicalMigration = options?.historicalMigration ?? false;
+ this._initPromise = Promise.resolve();
+ this._isInitialized = true;
+ this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
+ if (options?.evaluationEnvironments && !options?.evaluationContexts)
+ this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");
+ this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
+ }
+ logMsgIfDebug(fn) {
+ if (this.isDebug)
+ fn();
+ }
+ wrap(fn) {
+ if (this.disabled)
+ return void this._logger.warn("The client is disabled");
+ if (this._isInitialized)
+ return fn();
+ this._initPromise.then(() => fn());
+ }
+ getCommonEventProperties() {
+ return {
+ $lib: this.getLibraryId(),
+ $lib_version: this.getLibraryVersion()
+ };
+ }
+ get optedOut() {
+ return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
+ }
+ async optIn() {
+ this.wrap(() => {
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
+ });
+ }
+ async optOut() {
+ this.wrap(() => {
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
+ });
+ }
+ on(event, cb) {
+ return this._events.on(event, cb);
+ }
+ debug(enabled = true) {
+ this.removeDebugCallback?.();
+ if (enabled) {
+ const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
+ this.removeDebugCallback = () => {
+ removeDebugCallback();
+ this.removeDebugCallback = undefined;
+ };
+ }
+ }
+ get isDebug() {
+ return !!this.removeDebugCallback;
+ }
+ get isDisabled() {
+ return this.disabled;
+ }
+ buildPayload(payload) {
+ const userProperties = payload.properties || {};
+ let properties = {
+ ...userProperties,
+ ...this.getCommonEventProperties()
+ };
+ applyCallerFeatureFlagOverrides(properties, userProperties);
+ if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
+ properties = minimizeFlagCalledEventProperties(properties);
+ return {
+ distinct_id: payload.distinct_id,
+ event: payload.event,
+ properties
+ };
+ }
+ isMinimalFlagCalledEventsEnabled() {
+ return false;
+ }
+ addPendingPromise(promise) {
+ return this.promiseQueue.add(promise);
+ }
+ identifyStateless(distinctId, properties, options) {
+ this.wrap(() => {
+ const payload = {
+ ...this.buildPayload({
+ distinct_id: distinctId,
+ event: "$identify",
+ properties
+ })
+ };
+ this.enqueue("identify", payload, options);
+ });
+ }
+ async identifyStatelessImmediate(distinctId, properties, options) {
+ const payload = {
+ ...this.buildPayload({
+ distinct_id: distinctId,
+ event: "$identify",
+ properties
+ })
+ };
+ await this.sendImmediate("identify", payload, options);
+ }
+ captureStateless(distinctId, event, properties, options) {
+ this.wrap(() => {
+ const payload = this.buildPayload({
+ distinct_id: distinctId,
+ event,
+ properties
+ });
+ this.enqueue("capture", payload, options);
+ });
+ }
+ async captureStatelessImmediate(distinctId, event, properties, options) {
+ const payload = this.buildPayload({
+ distinct_id: distinctId,
+ event,
+ properties
+ });
+ await this.sendImmediate("capture", payload, options);
+ }
+ aliasStateless(alias, distinctId, properties, options) {
+ this.wrap(() => {
+ const payload = this.buildPayload({
+ event: "$create_alias",
+ distinct_id: distinctId,
+ properties: {
+ ...properties || {},
+ distinct_id: distinctId,
+ alias
+ }
+ });
+ this.enqueue("alias", payload, options);
+ });
+ }
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
+ const payload = this.buildPayload({
+ event: "$create_alias",
+ distinct_id: distinctId,
+ properties: {
+ ...properties || {},
+ distinct_id: distinctId,
+ alias
+ }
+ });
+ await this.sendImmediate("alias", payload, options);
+ }
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
+ this.wrap(() => {
+ const payload = this.buildPayload({
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
+ event: "$groupidentify",
+ properties: {
+ $group_type: groupType,
+ $group_key: groupKey,
+ $group_set: groupProperties || {},
+ ...eventProperties || {}
+ }
+ });
+ this.enqueue("capture", payload, options);
+ });
+ }
+ async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
+ const payload = this.buildPayload({
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
+ event: "$groupidentify",
+ properties: {
+ $group_type: groupType,
+ $group_key: groupKey,
+ $group_set: groupProperties || {},
+ ...eventProperties || {}
+ }
+ });
+ await this.sendImmediate("capture", payload, options);
+ }
+ async getRemoteConfig() {
+ await this._initPromise;
+ let host = this.host;
+ if (host === "https://us.i.posthog.com")
+ host = "https://us-assets.i.posthog.com";
+ else if (host === "https://eu.i.posthog.com")
+ host = "https://eu-assets.i.posthog.com";
+ const url = `${host}/array/${this.apiKey}/config`;
+ const fetchOptions = {
+ method: "GET",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json"
+ }
+ };
+ return this.fetchWithRetry(url, fetchOptions, {
+ type: "required",
+ consume: (response) => response.json()
+ }, {
+ retryCount: 0
+ }, this.remoteConfigRequestTimeoutMs).catch((error) => {
+ this._logger.error("Remote config could not be loaded", error);
+ this._events.emit("error", error);
+ });
+ }
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {
+ await this._initPromise;
+ const configParam = fetchConfig ? "&config=true" : "";
+ const url = `${this.host}/flags/?v=2${configParam}`;
+ const requestData = {
+ token: this.apiKey,
+ distinct_id: distinctId,
+ groups,
+ person_properties: personProperties,
+ group_properties: groupProperties,
+ ...extraPayload
+ };
+ if (personProperties.$device_id)
+ requestData.$device_id = personProperties.$device_id;
+ if (this.evaluationContexts && this.evaluationContexts.length > 0)
+ requestData.evaluation_contexts = this.evaluationContexts;
+ const evaluationRuntime = this.getEvaluationRuntime();
+ if (evaluationRuntime)
+ requestData.evaluation_runtime = evaluationRuntime;
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify(requestData)
+ };
+ this._logger.info("Flags URL", url);
+ return this.fetchWithRetry(url, fetchOptions, {
+ type: "required",
+ consume: (response) => response.json()
+ }, {
+ retryCount: this.featureFlagsRequestMaxRetries,
+ retryCheck: isRetryableFlagsFetchError
+ }, this.featureFlagsRequestTimeoutMs).then((response) => ({
+ success: true,
+ response: normalizeFlagsResponse(response)
+ })).catch((error) => {
+ this._events.emit("error", error);
+ return {
+ success: false,
+ error: this.categorizeRequestError(error)
+ };
+ });
+ }
+ categorizeRequestError(error) {
+ if (error instanceof PostHogFetchHttpError)
+ return {
+ type: "api_error",
+ statusCode: error.status
+ };
+ if (error instanceof PostHogFetchNetworkError) {
+ const cause = error.error;
+ if (cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError"))
+ return {
+ type: "timeout"
+ };
+ return {
+ type: "connection_error"
+ };
+ }
+ return {
+ type: "unknown_error"
+ };
+ }
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
+ await this._initPromise;
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
+ if (flagDetailResponse === undefined)
+ return {
+ response: undefined,
+ requestId: undefined
+ };
+ let response = getFeatureFlagValue(flagDetailResponse.response);
+ if (response === undefined)
+ response = false;
+ return {
+ response,
+ requestId: flagDetailResponse.requestId
+ };
+ }
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
+ await this._initPromise;
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
+ key
+ ]);
+ if (flagsResponse === undefined)
+ return;
+ const featureFlags = flagsResponse.flags;
+ const flagDetail = featureFlags[key];
+ return {
+ response: flagDetail,
+ requestId: flagsResponse.requestId,
+ evaluatedAt: flagsResponse.evaluatedAt
+ };
+ }
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
+ await this._initPromise;
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
+ key
+ ]);
+ if (!payloads)
+ return;
+ const response = payloads[key];
+ if (response === undefined)
+ return null;
+ return response;
+ }
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
+ return payloads;
+ }
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
+ }
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
+ if (!featureFlagDetails)
+ return {
+ flags: undefined,
+ payloads: undefined,
+ requestId: undefined
+ };
+ return {
+ flags: featureFlagDetails.featureFlags,
+ payloads: featureFlagDetails.featureFlagPayloads,
+ requestId: featureFlagDetails.requestId
+ };
+ }
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ const extraPayload = {
+ geoip_disable: disableGeoip ?? this.disableGeoip
+ };
+ if (flagKeysToEvaluate)
+ extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
+ const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
+ if (!result.success)
+ return;
+ const flagsResponse = result.response;
+ if (flagsResponse.errorsWhileComputingFlags)
+ console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");
+ if (flagsResponse.quotaLimited?.includes("feature_flags")) {
+ console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
+ return {
+ flags: {},
+ featureFlags: {},
+ featureFlagPayloads: {},
+ requestId: flagsResponse?.requestId,
+ quotaLimited: flagsResponse.quotaLimited
+ };
+ }
+ return flagsResponse;
+ }
+ async getSurveysStateless() {
+ await this._initPromise;
+ if (this.disabled)
+ return [];
+ if (this.disableSurveys === true) {
+ this._logger.info("Loading surveys is disabled.");
+ return [];
+ }
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
+ const fetchOptions = {
+ method: "GET",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json"
+ }
+ };
+ const response = await this.fetchWithRetry(url, fetchOptions, {
+ type: "required",
+ consume: (response) => {
+ if (response.status !== 200 || !response.json) {
+ const msg = `Surveys API could not be loaded: ${response.status}`;
+ const error = new Error(msg);
+ this._logger.error(error);
+ this._events.emit("error", new Error(msg));
+ return Promise.resolve(undefined);
+ }
+ return response.json();
+ }
+ }).catch((error) => {
+ this._logger.error("Surveys API could not be loaded", error);
+ this._events.emit("error", error);
+ });
+ const newSurveys = response?.surveys;
+ if (newSurveys)
+ this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
+ return newSurveys ?? [];
+ }
+ get props() {
+ if (!this._props)
+ this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
+ return this._props || {};
+ }
+ set props(val) {
+ this._props = val;
+ }
+ async register(properties) {
+ this.wrap(() => {
+ this.props = {
+ ...this.props,
+ ...properties
+ };
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
+ });
+ }
+ async unregister(property) {
+ this.wrap(() => {
+ delete this.props[property];
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
+ });
+ }
+ processBeforeEnqueue(message) {
+ return message;
+ }
+ async flushStorage() {}
+ getQueueRouteKey(_message) {
+ return DEFAULT_QUEUE_ROUTE;
+ }
+ persistedQueueKeyForRoute(_route) {
+ return types_PostHogPersistedProperty.Queue;
+ }
+ getActiveQueueRoutes() {
+ return [
+ DEFAULT_QUEUE_ROUTE
+ ];
+ }
+ getRouteQueue(route) {
+ return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
+ }
+ enqueue(type, _message, options, explicitRoute) {
+ this.wrap(() => {
+ if (this.optedOut)
+ return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
+ let message = this.prepareMessage(_message, options);
+ message = this.processBeforeEnqueue(message);
+ if (message === null)
+ return;
+ message = this.normalizeMessage(message);
+ const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
+ const queue = this.getPersistedProperty(queueKey) || [];
+ if (queue.length >= this.maxQueueSize) {
+ queue.shift();
+ this._logger.warn("Queue is full, the oldest event is dropped.");
+ }
+ queue.push({
+ message
+ });
+ this.setPersistedProperty(queueKey, queue);
+ this._events.emit(type, message);
+ if (queue.length >= this.flushAt)
+ this.flushBackground();
+ if (this.flushInterval && !this._flushTimer)
+ this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
+ });
+ }
+ async sendImmediate(type, _message, options, explicitRoute) {
+ if (this.disabled)
+ return void this._logger.warn("The client is disabled");
+ if (!this._isInitialized)
+ await this._initPromise;
+ if (this.optedOut)
+ return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
+ let message = this.prepareMessage(_message, options);
+ message = this.processBeforeEnqueue(message);
+ if (message === null)
+ return;
+ message = this.normalizeMessage(message);
+ try {
+ await this.sendBatch([
+ message
+ ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
+ } catch (err) {
+ this._events.emit("error", err);
+ }
+ }
+ normalizeMessage(message) {
+ const { type: _type, library, library_version, ...sanitizedMessage } = message;
+ let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
+ if (library !== undefined && properties?.$lib === undefined)
+ properties = {
+ ...properties || {},
+ $lib: library
+ };
+ if (library_version !== undefined && properties?.$lib_version === undefined)
+ properties = {
+ ...properties || {},
+ $lib_version: library_version
+ };
+ if (properties)
+ sanitizedMessage.properties = properties;
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
+ return sanitizedMessage;
+ }
+ normalizeTimestampForWire(timestamp) {
+ const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
+ if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
+ return timestamp;
+ const normalized = parsedTimestamp.toISOString();
+ const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
+ }
+ prepareMessage(_message, options) {
+ const message = {
+ ..._message,
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
+ uuid: getEventUuid(options?.uuid, uuidv7)
+ };
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
+ if (addGeoipDisableProperty) {
+ if (!isPostHogEventProperties(message.properties))
+ message.properties = {};
+ message.properties["$geoip_disable"] = true;
+ }
+ if (message.distinctId) {
+ message.distinct_id = message.distinctId;
+ delete message.distinctId;
+ }
+ return message;
+ }
+ clearFlushTimer() {
+ if (this._flushTimer) {
+ clearTimeout(this._flushTimer);
+ this._flushTimer = undefined;
+ }
+ }
+ flushBackground() {
+ if (this.pendingFlushPromise)
+ return;
+ this.flushAutomatic().catch(async (err) => {
+ await logFlushError(err);
+ });
+ }
+ flushAutomatic() {
+ return this.flush();
+ }
+ async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
+ const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
+ let iteration = 0;
+ while (true) {
+ const promises = this.promiseQueue.getPromises([
+ ...ignoredPendingPromises,
+ ...this.flushPromises
+ ], maxPromiseId);
+ if (promises.length === 0)
+ return;
+ if (iteration > 0)
+ this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
+ await Promise.all(promises.map((promise) => promise.catch(() => {})));
+ iteration++;
+ }
+ }
+ flushWithPendingPromises() {
+ return this.flushInternal(true);
+ }
+ flush() {
+ return this.flushInternal(false);
+ }
+ flushInternal(waitForPendingPromises) {
+ if (this.disabled)
+ return Promise.resolve();
+ if (!waitForPendingPromises && this.pendingFlushPromise)
+ return this.pendingFlushPromise;
+ const previousFlushPromise = this.flushPromise;
+ const maxPromiseId = this.promiseQueue.maxId;
+ const nextFlushPromise = Promise.resolve().then(() => {
+ if (waitForPendingPromises)
+ return this.waitForPendingPromises(maxPromiseId, [
+ previousFlushPromise,
+ nextFlushPromise
+ ]);
+ }).then(() => allSettled([
+ previousFlushPromise
+ ])).then(() => {
+ if (this.pendingFlushPromise === nextFlushPromise)
+ this.pendingFlushPromise = null;
+ return this._flush();
+ });
+ this.pendingFlushPromise = nextFlushPromise;
+ this.flushPromise = nextFlushPromise;
+ this.flushPromises.add(nextFlushPromise);
+ this.addPendingPromise(nextFlushPromise);
+ allSettled([
+ nextFlushPromise
+ ]).then(() => {
+ this.flushPromises.delete(nextFlushPromise);
+ if (this.pendingFlushPromise === nextFlushPromise)
+ this.pendingFlushPromise = null;
+ if (this.flushPromise === nextFlushPromise)
+ this.flushPromise = null;
+ });
+ return nextFlushPromise;
+ }
+ getCustomHeaders() {
+ const customUserAgent = this.getCustomUserAgent();
+ const headers = {};
+ if (customUserAgent && customUserAgent !== "")
+ headers["User-Agent"] = customUserAgent;
+ return headers;
+ }
+ compressPayload(payload) {
+ return gzipCompress(payload, this.isDebug);
+ }
+ getBatchEndpointPath(_route) {
+ return "/batch/";
+ }
+ async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
+ const data = {
+ api_key: this.apiKey,
+ batch: batchMessages.map((message) => {
+ if (!message)
+ return message;
+ const timestamp = this.normalizeTimestampForWire(message.timestamp);
+ return timestamp === message.timestamp ? message : {
+ ...message,
+ timestamp
+ };
+ }),
+ sent_at: currentISOTime()
+ };
+ if (this.historicalMigration)
+ data.historical_migration = true;
+ const payload = safeJsonStringify(data);
+ const url = `${this.host}${this.getBatchEndpointPath(route)}`;
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json",
+ ...gzippedPayload !== null && {
+ "Content-Encoding": "gzip"
+ }
+ },
+ body: gzippedPayload || payload
+ };
+ await this.fetchWithRetry(url, fetchOptions, {
+ type: "successful-write"
+ }, retryOptions);
+ }
+ async _flush() {
+ this.clearFlushTimer();
+ await this._initPromise;
+ const routes = this.getActiveQueueRoutes();
+ if (!routes.some((route) => this.getRouteQueue(route).length > 0))
+ return;
+ const sentMessages = [];
+ let firstError;
+ for (const route of routes)
+ try {
+ await this._flushRoute(route, sentMessages);
+ } catch (err) {
+ if (firstError === undefined)
+ firstError = err;
+ }
+ if (firstError !== undefined)
+ throw firstError;
+ this._events.emit("flush", sentMessages);
+ }
+ async _flushRoute(route, sentMessages) {
+ const queueKey = this.persistedQueueKeyForRoute(route);
+ let queue = this.getPersistedProperty(queueKey) || [];
+ if (!queue.length)
+ return;
+ const originalQueueLength = queue.length;
+ let sentFromRoute = 0;
+ while (queue.length > 0 && sentFromRoute < originalQueueLength) {
+ const batchItems = queue.slice(0, this.maxBatchSize);
+ const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
+ const persistQueueChange = async () => {
+ const refreshedQueue = this.getPersistedProperty(queueKey) || [];
+ const remainingBatchItems = [
+ ...batchItems
+ ];
+ const newQueue = refreshedQueue.filter((item) => {
+ const itemUuid = item.message?.uuid;
+ const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
+ if (batchItemIndex === -1)
+ return true;
+ remainingBatchItems.splice(batchItemIndex, 1);
+ return false;
+ });
+ this.setPersistedProperty(queueKey, newQueue);
+ queue = newQueue;
+ this._dequeuedMessagesCount += batchItems.length;
+ await this.flushStorage();
+ };
+ const retryOptions = {
+ retryCheck: (err) => {
+ if (isPostHogFetchContentTooLargeError(err))
+ return false;
+ return isPostHogFetchRetryableError(err);
+ }
+ };
+ try {
+ await this.sendBatch(batchMessages, retryOptions, route);
+ } catch (err) {
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
+ this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
+ continue;
+ }
+ if (!(err instanceof PostHogFetchNetworkError))
+ await persistQueueChange();
+ this._events.emit("error", err);
+ throw err;
+ }
+ await persistQueueChange();
+ sentMessages.push(...batchMessages);
+ sentFromRoute += batchMessages.length;
+ }
+ }
+ async _sendOtlpBatch({ path, auth, payload }) {
+ if (this.disabled)
+ return {
+ kind: "fatal",
+ error: new Error("The client is disabled")
+ };
+ let serialized;
+ try {
+ serialized = JSON.stringify(payload);
+ } catch (error) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Could not serialize a ${path} batch; reporting it as too large`, error));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const payloadBytes = byteLengthOf(serialized);
+ if (payloadBytes > OTLP_MAX_BODY_BYTES) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Not sending a ${path} batch of ${payloadBytes} bytes: the endpoint accepts at most ${OTLP_MAX_BODY_BYTES}`));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const url = auth === "bearer" ? `${this.host}/i/v1/${path}` : `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
+ const body = gzippedPayload || serialized;
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json",
+ ...auth === "bearer" && {
+ Authorization: `Bearer ${this.apiKey}`
+ },
+ ...gzippedPayload !== null && {
+ "Content-Encoding": "gzip"
+ }
+ },
+ body
+ };
+ try {
+ await this.fetchWithRetry(url, fetchOptions, {
+ type: "successful-write"
+ }, {
+ retryCheck: (err) => {
+ if (isPostHogFetchContentTooLargeError(err))
+ return false;
+ if (err instanceof PostHogFetchHttpError && err.retryAfterMs !== undefined)
+ return false;
+ return isPostHogFetchRetryableError(err);
+ }
+ });
+ return {
+ kind: "ok"
+ };
+ } catch (err) {
+ if (isPostHogFetchContentTooLargeError(err))
+ return {
+ kind: "too-large"
+ };
+ if (isPostHogFetchRetryableError(err)) {
+ const retryAfterMs = err instanceof PostHogFetchHttpError ? err.retryAfterMs : undefined;
+ return {
+ kind: "retry-later",
+ error: err,
+ ...retryAfterMs !== undefined && {
+ retryAfterMs
+ }
+ };
+ }
+ return {
+ kind: "fatal",
+ error: err
+ };
+ }
+ }
+ async _sendLogsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "logs",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendMetricsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "metrics",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendTracesBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "traces",
+ auth: "bearer",
+ payload
+ });
+ }
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
+ const body = options.body ? options.body : "";
+ const reqByteLength = byteLengthOf(body);
+ const retriableOptions = {
+ ...this._retryOptions,
+ ...retryOptions
+ };
+ let attempt = 0;
+ return await retriable(async () => {
+ attempt++;
+ const ctrl = new AbortController;
+ const timeoutMs = requestTimeout ?? this.requestTimeout;
+ const requestDeadline = Date.now() + timeoutMs;
+ let timer;
+ const deadline = new Promise((_resolve, reject) => {
+ timer = safeSetTimeout(() => {
+ const timeoutError = createNamedError("AbortError", `Request timed out after ${timeoutMs}ms`);
+ reject(timeoutError);
+ ctrl.abort(timeoutError);
+ }, timeoutMs);
+ });
+ let res;
+ let responseAccepted = false;
+ let cancellation;
+ const cancelBody = () => cancellation ??= (async () => {
+ try {
+ await res?.body?.cancel();
+ } catch {}
+ })();
+ try {
+ let fetchPromise;
+ try {
+ fetchPromise = this.fetch(url, {
+ signal: ctrl.signal,
+ ...options
+ });
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ fetchPromise.then((lateResponse) => {
+ if (ctrl.signal.aborted && !responseAccepted)
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
+ }).catch(() => {});
+ try {
+ res = await Promise.race([
+ fetchPromise,
+ deadline
+ ]);
+ responseAccepted = true;
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ const isNoCors = options.mode === "no-cors";
+ const maxSuccessStatus = responseHandling.type === "successful-write" ? 300 : 400;
+ if (!isNoCors && (res.status < 200 || res.status >= maxSuccessStatus))
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
+ if (responseHandling.type === "successful-write") {
+ try {
+ await Promise.race([
+ cancelBody(),
+ deadline
+ ]);
+ } catch {}
+ return;
+ }
+ try {
+ return await Promise.race([
+ responseHandling.consume(res),
+ deadline
+ ]);
+ } catch (e) {
+ if (ctrl.signal.aborted)
+ throw new PostHogFetchNetworkError(e);
+ throw e;
+ }
+ } finally {
+ clearTimeout(timer);
+ if (ctrl.signal.aborted && res)
+ cancelBody();
+ }
+ }, {
+ ...retriableOptions,
+ retryCheck: (error) => {
+ const shouldRetry = retriableOptions.retryCheck(error);
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
+ error.cancelResponseBody();
+ return shouldRetry;
+ }
+ });
+ }
+ async _shutdown(shutdownTimeoutMs = 30000) {
+ await this._initPromise;
+ let hasTimedOut = false;
+ this.clearFlushTimer();
+ if (this.disabled)
+ return;
+ const doShutdown = async () => {
+ try {
+ await this.promiseQueue.join();
+ while (true) {
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
+ if (!hasQueuedEvents)
+ break;
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
+ await this.flush();
+ if (hasTimedOut)
+ break;
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
break;
}
}
- if (frames.length >= STACKTRACE_FRAME_LIMIT)
- break;
+ } catch (e) {
+ if (!isPostHogFetchError(e))
+ throw e;
+ await logFlushError(e);
}
- }
- return reverseAndStripFrames(frames);
- };
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
-class ErrorCoercer {
- match(err) {
- return isError(err);
- }
- coerce(err, ctx) {
- const stack = this.getStack(err);
- const synthetic = stack === undefined;
- return {
- type: this.getType(err),
- value: this.getMessage(err, ctx),
- stack: stack ?? ctx.syntheticException?.stack,
- cause: err.cause ? ctx.next(err.cause) : undefined,
- synthetic
- };
- }
- getType(err) {
- return err.name || err.constructor.name;
- }
- getMessage(err, _ctx) {
- const message = err.message;
- if (message.error && typeof message.error.message == "string")
- return String(message.error.message);
- return String(message);
- }
- getStack(err) {
- return err.stacktrace || err.stack || undefined;
- }
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
-var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
-
-class StringCoercer {
- match(input) {
- return typeof input == "string";
- }
- coerce(input, ctx) {
- const [type, value] = this.getInfos(input);
- return {
- type: type ?? "Error",
- value: value ?? input,
- stack: ctx.syntheticException?.stack,
- synthetic: true
};
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
+ shutdownTimeoutMs
+ });
+ hasTimedOut = true;
+ });
}
- getInfos(candidate) {
- let type = "Error";
- let value = candidate;
- const groups = candidate.match(ERROR_TYPES_PATTERN);
- if (groups) {
- type = groups[1];
- value = groups[2];
- }
- return [
- type,
- value
- ];
+ async shutdown(shutdownTimeoutMs = 30000) {
+ if (this.shutdownPromise)
+ this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
+ else
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
+ this.shutdownPromise = null;
+ });
+ return this.shutdownPromise;
}
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
-var severityLevels = [
- "fatal",
- "error",
- "warning",
- "log",
- "info",
- "debug"
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.mjs
+var NULL_VALUES_ALLOWED_OPERATORS = [
+ "is_not",
+ "is_set"
];
+var LONG_SCALE = 1152921504606847000;
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
-function extractExceptionKeysForMessage(err, maxLength = 40) {
- const keys = Object.keys(err);
- keys.sort();
- if (!keys.length)
- return "[object has no keys]";
- for (let i = keys.length;i > 0; i--) {
- const serialized = keys.slice(0, i).join(", ");
- if (!(serialized.length > maxLength)) {
- if (i === keys.length)
- return serialized;
- return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
- }
+class InconclusiveMatchError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = this.constructor.name;
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
}
- return "";
}
-
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
-class ObjectCoercer {
- match(candidate) {
- return typeof candidate == "object" && candidate !== null;
- }
- coerce(candidate, ctx) {
- const errorProperty = this.getErrorPropertyFromObject(candidate);
- if (errorProperty)
- return ctx.apply(errorProperty);
- return {
- type: this.getType(candidate),
- value: this.getValue(candidate),
- stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
- level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
- synthetic: true
- };
- }
- getType(err) {
- if (isEvent(err))
- return err.constructor.name;
- const name = "name" in err ? err.name : undefined;
- return isString(name) && !isEmptyString(name) ? name : "Error";
- }
- getValue(err) {
- if ("name" in err && typeof err.name == "string") {
- let message = `'${err.name}' captured as exception`;
- if ("message" in err && typeof err.message == "string")
- message += ` with message: '${err.message}'`;
- return message;
- }
- if ("message" in err && typeof err.message == "string")
- return err.message;
- const className = this.getObjectClassName(err);
- const keys = extractExceptionKeysForMessage(err);
- return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
+function isTruthyOrFalsyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return true;
+ if (typeof value == "string") {
+ const lowercaseValue = value.toLowerCase();
+ return lowercaseValue === "true" || lowercaseValue === "false";
}
- isSeverityLevel(x) {
- return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyOrFalsyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function isTruthyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return value;
+ if (typeof value == "string")
+ return value.toLowerCase() === "true";
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function assertUnicodeScalarString(value) {
+ for (let index = 0;index < value.length; index++) {
+ const unit = value.charCodeAt(index);
+ if (unit >= 55296 && unit <= 56319) {
+ const next = value.charCodeAt(index + 1);
+ if (index + 1 >= value.length || next < 56320 || next > 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ index++;
+ } else if (unit >= 56320 && unit <= 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ }
+}
+function assertJsonRepresentable(value, seen = new Set) {
+ if (value === null || typeof value == "boolean")
+ return;
+ if (typeof value == "string")
+ return void assertUnicodeScalarString(value);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot represent non-finite number ${value} like the flags service`);
+ return;
}
- getStack(candidate) {
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular array during local evaluation");
+ seen.add(value);
try {
- if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
- return candidate.stacktrace;
- return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
- } catch {
- return;
+ for (let index = 0;index < value.length; index++)
+ if (index in value)
+ assertJsonRepresentable(value[index], seen);
+ } finally {
+ seen.delete(value);
}
+ return;
}
- getErrorPropertyFromObject(obj) {
- for (const prop in obj)
- if (Object.prototype.hasOwnProperty.call(obj, prop)) {
- const value = obj[prop];
- if (isError(value))
- return value;
- }
- }
- getObjectClassName(obj) {
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot represent a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular object during local evaluation");
+ seen.add(value);
try {
- const prototype = Object.getPrototypeOf(obj);
- return prototype ? prototype.constructor.name : undefined;
- } catch (e) {
- return;
+ for (const key of Object.keys(value)) {
+ assertUnicodeScalarString(key);
+ assertJsonRepresentable(value[key], seen);
+ }
+ } finally {
+ seen.delete(value);
}
+ return;
}
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
-class EventCoercer {
- match(err) {
- return isEvent(err);
- }
- coerce(evt, ctx) {
- const constructorName = evt.constructor.name;
- return {
- type: constructorName,
- value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
- stack: ctx.syntheticException?.stack,
- synthetic: true
- };
- }
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
-class PrimitiveCoercer {
- match(candidate) {
- return isPrimitive(candidate);
- }
- coerce(value, ctx) {
- return {
- type: "Error",
- value: `Primitive value captured as exception: ${String(value)}`,
- stack: ctx.syntheticException?.stack,
- synthetic: true
- };
- }
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
-class ReduceableCache {
- constructor(_maxSize) {
- this._maxSize = _maxSize;
- this._cache = new Map;
- }
- get(key) {
- const value = this._cache.get(key);
- if (value === undefined)
- return;
- this._cache.delete(key);
- this._cache.set(key, value);
- return value;
+ throw new InconclusiveMatchError(`Cannot represent ${typeof value} like the flags service`);
+}
+function compareJsonObjectKeys(left, right) {
+ let leftIndex = 0;
+ let rightIndex = 0;
+ while (leftIndex < left.length && rightIndex < right.length) {
+ const leftUnit = left.charCodeAt(leftIndex);
+ const rightUnit = right.charCodeAt(rightIndex);
+ const leftIsHighSurrogate = leftUnit >= 55296 && leftUnit <= 56319;
+ const rightIsHighSurrogate = rightUnit >= 55296 && rightUnit <= 56319;
+ const leftNext = leftIsHighSurrogate ? left.charCodeAt(leftIndex + 1) : 0;
+ const rightNext = rightIsHighSurrogate ? right.charCodeAt(rightIndex + 1) : 0;
+ const leftCodePoint = leftIsHighSurrogate ? (leftUnit - 55296) * 1024 + leftNext - 56320 + 65536 : leftUnit;
+ const rightCodePoint = rightIsHighSurrogate ? (rightUnit - 55296) * 1024 + rightNext - 56320 + 65536 : rightUnit;
+ if (leftCodePoint !== rightCodePoint)
+ return leftCodePoint - rightCodePoint;
+ leftIndex += leftIsHighSurrogate ? 2 : 1;
+ rightIndex += rightIsHighSurrogate ? 2 : 1;
+ }
+ return left.length - right.length;
+}
+function serializeJsonValue(value, seen = new Set) {
+ if (value === null)
+ return "null";
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return JSON.stringify(value);
}
- set(key, value) {
- this._cache.set(key, value);
+ if (typeof value == "boolean")
+ return value ? "true" : "false";
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot stringify non-finite number ${value} like the flags service`);
+ if (Number.isInteger(value))
+ throw new InconclusiveMatchError(`Cannot distinguish integer ${value} from an integral JSON float during local evaluation`);
+ return String(value);
+ }
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular array during local evaluation");
+ seen.add(value);
+ try {
+ const items = [];
+ for (let index = 0;index < value.length; index++)
+ items.push(index in value ? serializeJsonValue(value[index], seen) : "null");
+ return `[${items.join(",")}]`;
+ } finally {
+ seen.delete(value);
+ }
}
- reduce() {
- while (this._cache.size >= this._maxSize) {
- const value = this._cache.keys().next().value;
- if (value)
- this._cache.delete(value);
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot stringify a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular object during local evaluation");
+ seen.add(value);
+ try {
+ const keys = Object.keys(value);
+ keys.forEach(assertUnicodeScalarString);
+ return `{${keys.sort(compareJsonObjectKeys).map((key) => `${JSON.stringify(key)}:${serializeJsonValue(value[key], seen)}`).join(",")}}`;
+ } finally {
+ seen.delete(value);
}
}
+ throw new InconclusiveMatchError(`Cannot stringify ${typeof value} like the flags service`);
}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
-var EXCEPTION_STEP_INTERNAL_FIELDS = {
- MESSAGE: "$message",
- TIMESTAMP: "$timestamp"
-};
-var RESERVED_EXCEPTION_STEP_KEYS = new Set([
- EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
- EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
-]);
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
-function getInjectedReleaseId() {
- const injected = globalThis._posthogReleaseId;
- return typeof injected == "string" && injected.length > 0 ? injected : undefined;
-}
-// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
-class PostHogFetchHttpError extends Error {
- constructor(response, reqByteLength, responseBodyDeadline, abortController) {
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
- }
- get status() {
- return this.response.status;
- }
- get bodyReadTimedOut() {
- return this._bodyReadTimedOut;
+function exactMatchString(value) {
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return value;
}
- get text() {
- if (!this.responseBodyTextPromise)
- if (Date.now() >= this.responseBodyDeadline) {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- this.cancelResponseBody(timeoutError);
- this.responseBodyTextPromise = Promise.reject(timeoutError);
- } else {
- const responseBodyTimeout = new Promise((_resolve, reject) => {
- this.responseBodyTimer = safeSetTimeout(() => {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- reject(timeoutError);
- this.cancelResponseBody(timeoutError);
- }, this.responseBodyDeadline - Date.now());
- });
- let responseBodyText;
- try {
- responseBodyText = Promise.resolve(this.response.text());
- } catch (error) {
- responseBodyText = Promise.reject(error);
- }
- this.responseBodyTextPromise = Promise.race([
- responseBodyText,
- responseBodyTimeout
- ]).finally(() => clearTimeout(this.responseBodyTimer));
- }
- return this.responseBodyTextPromise;
+ return serializeJsonValue(value);
+}
+function isValidRegex(regex) {
+ try {
+ new RegExp(regex);
+ return true;
+ } catch {
+ return false;
}
- get json() {
- return this.text.then((text) => JSON.parse(text));
+}
+function asciiLowercase(value) {
+ return String(value).replace(/[A-Z]/g, (character) => character.toLowerCase());
+}
+function parseSemverNumericIdentifier(part, raw, parsingPolicy) {
+ if (!/^\d+$/.test(part) || parsingPolicy === "strict" && part.length > 1 && part[0] === "0")
+ throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
+ return parseInt(part, 10);
+}
+function parseFeatureFlagSemver(value, parsingPolicy = "strict") {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const baseVersion = text.split("-")[0].split("+")[0];
+ if (!baseVersion || baseVersion.startsWith("."))
+ throw new InconclusiveMatchError(`Invalid semver: ${value}`);
+ const parts = baseVersion.split(".");
+ const parsePart = (part) => {
+ if (part === undefined || part === "")
+ return 0;
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
+ };
+ return [
+ parsePart(parts[0]),
+ parsePart(parts[1]),
+ parsePart(parts[2])
+ ];
+}
+function compareSemverTuples(a, b) {
+ for (let i = 0;i < 3; i++) {
+ if (a[i] < b[i])
+ return -1;
+ if (a[i] > b[i])
+ return 1;
}
- cancelResponseBody(reason) {
- clearTimeout(this.responseBodyTimer);
- if (!this.abortController.signal.aborted)
- this.abortController.abort(reason);
- (async () => {
+ return 0;
+}
+function computeTildeBounds(value, parsingPolicy) {
+ const parsed = parseFeatureFlagSemver(value, parsingPolicy);
+ return {
+ lower: [
+ parsed[0],
+ parsed[1],
+ parsed[2]
+ ],
+ upper: [
+ parsed[0],
+ parsed[1] + 1,
+ 0
+ ]
+ };
+}
+function computeCaretBounds(value, parsingPolicy) {
+ const [major, minor, patch] = parseFeatureFlagSemver(value, parsingPolicy);
+ const lower = [
+ major,
+ minor,
+ patch
+ ];
+ let upper;
+ upper = major > 0 ? [
+ major + 1,
+ 0,
+ 0
+ ] : minor > 0 ? [
+ 0,
+ minor + 1,
+ 0
+ ] : [
+ 0,
+ 0,
+ patch + 1
+ ];
+ return {
+ lower,
+ upper
+ };
+}
+function computeWildcardBounds(value, parsingPolicy) {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
+ if (!cleanedText)
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ const parts = cleanedText.split(".");
+ const parseWildcardPart = (part) => {
+ if (parsingPolicy === "legacy-permissive") {
+ const parsed = parseInt(part, 10);
+ if (!isNaN(parsed))
+ return parsed;
+ } else
try {
- await this.response.body?.cancel();
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
} catch {}
- })();
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ };
+ const major = parseWildcardPart(parts[0]);
+ if (parts.length === 1)
+ return {
+ lower: [
+ major,
+ 0,
+ 0
+ ],
+ upper: [
+ major + 1,
+ 0,
+ 0
+ ]
+ };
+ const minor = parseWildcardPart(parts[1]);
+ return {
+ lower: [
+ major,
+ minor,
+ 0
+ ],
+ upper: [
+ major,
+ minor + 1,
+ 0
+ ]
+ };
+}
+function convertToDateTime(value) {
+ if (value instanceof Date)
+ return value;
+ if (typeof value == "string" || typeof value == "number") {
+ const date = new Date(value);
+ if (!isNaN(date.valueOf()))
+ return date;
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
}
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
}
-
-class PostHogFetchNetworkError extends Error {
- constructor(error) {
- super("Network error while fetching PostHog", error instanceof Error ? {
- cause: error
- } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+function relativeDateParseForFeatureFlagMatching(value) {
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
+ const match = value.match(regex);
+ const parsedDt = new Date(new Date().toISOString());
+ if (!match || !match.groups)
+ return null;
+ const number = parseInt(match.groups["number"]);
+ if (number >= 1e4)
+ return null;
+ const interval = match.groups["interval"];
+ if (interval === "h")
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
+ else if (interval === "d")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
+ else if (interval === "w")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
+ else if (interval === "m")
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
+ else {
+ if (interval !== "y")
+ return null;
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
}
+ return parsedDt;
}
-var applyCallerFeatureFlagOverrides = (target, callerProperties) => {
- for (const key of Object.keys(callerProperties))
- if (key.startsWith("$feature/") || key === "$active_feature_flags")
- target[key] = callerProperties[key];
-};
-async function logFlushError(err) {
- if (err instanceof PostHogFetchHttpError) {
- let text = "";
- try {
- text = await err.text;
- } catch {
- if (err.bodyReadTimedOut)
- text = "<response body read timed out>";
- }
- console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
+function matchFeatureFlagProperty(property, propertyValues, options = {}) {
+ const key = property.key;
+ const value = property.value;
+ const operator = property.operator || "exact";
+ const parsingPolicy = options.semverParsingPolicy ?? "strict";
+ const hasProperty = Object.prototype.hasOwnProperty.call(propertyValues, key);
+ if (hasProperty) {
+ if (operator === "is_not_set")
+ return false;
+ else if (operator === "is_set")
+ return true;
} else
- console.error("Error while flushing PostHog", err);
- return Promise.resolve();
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
+ const overrideValue = propertyValues[key];
+ if (overrideValue === undefined) {
+ options.warnFunction?.(`Property ${key} cannot have a value of undefined with the ${operator} operator`);
+ return operator === "is_not";
+ }
+ if (overrideValue === null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator) && operator !== "exact" && operator !== "is_not") {
+ options.warnFunction?.(`Property ${key} cannot have a value of null with the ${operator} operator`);
+ return false;
+ }
+ const computeExactMatch = (target, actual) => {
+ if (isTruthyOrFalsyPropertyValue(target)) {
+ assertJsonRepresentable(actual);
+ return isTruthyPropertyValue(target) === isTruthyPropertyValue(actual);
+ }
+ if (Array.isArray(target)) {
+ const actualString = exactMatchString(actual).toLowerCase();
+ return target.some((item) => exactMatchString(item).toLowerCase() === actualString);
+ }
+ return exactMatchString(target).toLowerCase() === exactMatchString(actual).toLowerCase();
+ };
+ const compare = (lhs, rhs, comparisonOperator) => {
+ if (comparisonOperator === "gt")
+ return lhs > rhs;
+ if (comparisonOperator === "gte")
+ return lhs >= rhs;
+ if (comparisonOperator === "lt")
+ return lhs < rhs;
+ if (comparisonOperator === "lte")
+ return lhs <= rhs;
+ throw new Error(`Invalid operator: ${comparisonOperator}`);
+ };
+ switch (operator) {
+ case "exact":
+ return computeExactMatch(value, overrideValue);
+ case "is_not":
+ return !computeExactMatch(value, overrideValue);
+ case "is_set":
+ return true;
+ case "icontains":
+ return asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "not_icontains":
+ return !asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "starts_with":
+ return asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "not_starts_with":
+ return !asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "ends_with":
+ return asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "not_ends_with":
+ return !asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
+ case "not_regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
+ case "gt":
+ case "gte":
+ case "lt":
+ case "lte": {
+ const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
+ const parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : 0 / 0;
+ if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
+ return compare(parsedOverride, parsedValue, operator);
+ return compare(String(overrideValue), String(value), operator);
+ }
+ case "is_date_after":
+ case "is_date_before": {
+ if (typeof value == "boolean")
+ throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
+ if (parsedDate == null)
+ parsedDate = convertToDateTime(value);
+ const overrideDate = convertToDateTime(overrideValue);
+ return operator === "is_date_before" ? overrideDate < parsedDate : overrideDate > parsedDate;
+ }
+ case "semver_eq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) === 0;
+ case "semver_neq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) !== 0;
+ case "semver_gt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) > 0;
+ case "semver_gte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) >= 0;
+ case "semver_lt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) < 0;
+ case "semver_lte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) <= 0;
+ case "semver_tilde": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeTildeBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_caret": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeCaretBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_wildcard": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeWildcardBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ default:
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
+ }
}
-function isPostHogFetchError(err) {
- return typeof err == "object" && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));
+async function hashSHA1(text) {
+ const subtle = globalThis.crypto?.subtle;
+ if (!subtle)
+ throw new Error("SubtleCrypto API not available");
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
+ return Array.from(new Uint8Array(hashBuffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
-function isPostHogFetchNetworkError(err) {
- return err instanceof PostHogFetchNetworkError;
+async function getFeatureFlagHash(key, bucketingValue, salt = "") {
+ const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
}
-function isRetryableFlagsFetchError(err) {
- if (err instanceof PostHogFetchHttpError)
- return err.status === 502 || err.status === 504;
- if (!(err instanceof PostHogFetchNetworkError))
- return false;
- const cause = err.error;
- const code = cause?.code ?? cause?.cause?.code;
- return code !== "ECONNREFUSED";
+function getFeatureFlagVariantLookupTable(variants) {
+ const table = [];
+ let valueMin = 0;
+ for (const variant of variants) {
+ const valueMax = valueMin + variant.rollout_percentage / 100;
+ table.push({
+ valueMin,
+ valueMax,
+ key: variant.key
+ });
+ valueMin = valueMax;
+ }
+ return table;
}
-function isPostHogFetchContentTooLargeError(err) {
- return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
+async function getFeatureFlagVariant(key, bucketingValue, variants) {
+ const hashValue = await getFeatureFlagHash(key, bucketingValue, "variant");
+ return getFeatureFlagVariantLookupTable(variants).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax)?.key;
}
-function isPostHogFetchRetryableError(err) {
- if (err instanceof PostHogFetchHttpError)
- return err.status === 408 || err.status === 429 || err.status >= 500;
- return isPostHogFetchNetworkError(err);
+function resolveFeatureFlagPayload(payloads, flagValue) {
+ if (flagValue === false || flagValue == null || !payloads)
+ return null;
+ const payloadKey = typeof flagValue == "boolean" ? flagValue.toString() : flagValue;
+ const payload = payloads[payloadKey] || null;
+ return payload == null ? null : parsePayload(payload);
}
-function isPostHogEventProperties(value) {
- return value !== null && typeof value == "object" && !Array.isArray(value);
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-any-value.mjs
+var INT64_RANGE_LIMIT = 9223372036854776000;
+var INT64_RANGE_LIMIT_DECIMAL = "9223372036854775808";
+var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
+function newState() {
+ return {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ };
}
-var DEFAULT_QUEUE_ROUTE = "default";
-
-class PostHogCoreStateless {
- getErrorPropertiesBuilder() {
- if (!this._errorPropertiesBuilder)
- this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();
- return this._errorPropertiesBuilder;
- }
- createErrorPropertiesBuilder() {
- return new ErrorPropertiesBuilder([
- new ErrorCoercer,
- new ObjectCoercer,
- new StringCoercer,
- new PrimitiveCoercer
- ], createDefaultStackParser());
+function toOtlpKeyValueList(attrs, logger) {
+ try {
+ return encodeKeyValueList(attrs, logger, newState(), 0);
+ } catch {
+ return [];
}
- constructor(apiKey, options = {}) {
- this.flushPromise = null;
- this.pendingFlushPromise = null;
- this.flushPromises = new Set;
- this._dequeuedMessagesCount = 0;
- this.shutdownPromise = null;
- this.promiseQueue = new PromiseQueue;
- this._events = new SimpleEventEmitter;
- this._isInitialized = false;
- const normalizedApiKey = typeof apiKey == "string" ? apiKey.trim() : "";
- const normalizedHost = typeof options.host == "string" ? options.host.trim() : "";
- const missingApiKey = !normalizedApiKey;
- this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
- if (missingApiKey)
- this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");
- this.apiKey = normalizedApiKey;
- this.host = removeTrailingSlash(normalizedHost || "https://us.i.posthog.com");
- this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
- this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
- this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);
- this.flushInterval = options.flushInterval ?? 1e4;
- this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
- this.defaultOptIn = options.defaultOptIn ?? true;
- this.disableSurveys = options.disableSurveys ?? false;
- this._retryOptions = {
- retryCount: options.fetchRetryCount ?? 3,
- retryDelay: options.fetchRetryDelay ?? 3000,
- retryCheck: isPostHogFetchRetryableError
+}
+function encodeBigInt(value, logger) {
+ const decimal = value.toString();
+ const limit = BigInt(INT64_RANGE_LIMIT_DECIMAL);
+ if (value >= limit || value < -limit) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
};
- this.requestTimeout = options.requestTimeout ?? 1e4;
- this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
- this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
- this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
- this.disableGeoip = options.disableGeoip ?? true;
- this.disabled = (options.disabled ?? false) || missingApiKey;
- this.historicalMigration = options?.historicalMigration ?? false;
- this._initPromise = Promise.resolve();
- this._isInitialized = true;
- this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
- if (options?.evaluationEnvironments && !options?.evaluationContexts)
- this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");
- this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
- }
- logMsgIfDebug(fn) {
- if (this.isDebug)
- fn();
}
- wrap(fn) {
- if (this.disabled)
- return void this._logger.warn("The client is disabled");
- if (this._isInitialized)
- return fn();
- this._initPromise.then(() => fn());
- }
- getCommonEventProperties() {
+ return {
+ intValue: decimal
+ };
+}
+function encodeAnyValue(value, logger, state, depth) {
+ if (state.remainingNodes <= 0)
return {
- $lib: this.getLibraryId(),
- $lib_version: this.getLibraryVersion()
+ stringValue: TRUNCATED_VALUE
};
- }
- get optedOut() {
- return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
- }
- async optIn() {
- this.wrap(() => {
- this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
- });
- }
- async optOut() {
- this.wrap(() => {
- this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
- });
- }
- on(event, cb) {
- return this._events.on(event, cb);
- }
- debug(enabled = true) {
- this.removeDebugCallback?.();
- if (enabled) {
- const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
- this.removeDebugCallback = () => {
- removeDebugCallback();
- this.removeDebugCallback = undefined;
+ state.remainingNodes--;
+ if (isBoolean(value))
+ return {
+ boolValue: value
+ };
+ if (typeof value == "bigint")
+ return encodeBigInt(value, logger);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ return {
+ stringValue: String(value)
+ };
+ if (Number.isInteger(value)) {
+ if (Number.isSafeInteger(value))
+ return {
+ intValue: String(value)
+ };
+ if ("u" < typeof BigInt)
+ return {
+ stringValue: String(value)
+ };
+ const decimal = BigInt(value).toString();
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
+ };
+ }
+ return {
+ intValue: decimal
};
}
+ return {
+ doubleValue: value
+ };
}
- get isDebug() {
- return !!this.removeDebugCallback;
- }
- get isDisabled() {
- return this.disabled;
- }
- buildPayload(payload) {
- const userProperties = payload.properties || {};
- let properties = {
- ...userProperties,
- ...this.getCommonEventProperties()
+ if (typeof value == "string")
+ return {
+ stringValue: sanitizeString(value)
};
- applyCallerFeatureFlagOverrides(properties, userProperties);
- if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
- properties = minimizeFlagCalledEventProperties(properties);
+ if (typeof value == "function")
return {
- distinct_id: payload.distinct_id,
- event: payload.event,
- properties
+ stringValue: FUNCTION_VALUE
};
- }
- isMinimalFlagCalledEventsEnabled() {
- return false;
- }
- addPendingPromise(promise) {
- return this.promiseQueue.add(promise);
- }
- identifyStateless(distinctId, properties, options) {
- this.wrap(() => {
- const payload = {
- ...this.buildPayload({
- distinct_id: distinctId,
- event: "$identify",
- properties
- })
- };
- this.enqueue("identify", payload, options);
- });
- }
- async identifyStatelessImmediate(distinctId, properties, options) {
- const payload = {
- ...this.buildPayload({
- distinct_id: distinctId,
- event: "$identify",
- properties
- })
+ if (typeof value == "symbol")
+ return {
+ stringValue: String(value)
};
- await this.sendImmediate("identify", payload, options);
+ if (typeof value == "object" && value !== null) {
+ if (state.ancestors.has(value))
+ return {
+ stringValue: CIRCULAR_VALUE
+ };
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return {
+ stringValue: TRUNCATED_VALUE
+ };
+ if (value instanceof Date) {
+ const time = value.getTime();
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
+ return {
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ };
+ }
+ state.ancestors.add(value);
+ try {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
+ return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
+ } catch {}
+ if (isArray(value))
+ return {
+ arrayValue: {
+ values: encodeArrayValues(value, logger, state, depth + 1)
+ }
+ };
+ return {
+ kvlistValue: {
+ values: encodeKeyValueList(value, logger, state, depth + 1)
+ }
+ };
+ } finally {
+ state.ancestors.delete(value);
+ }
}
- captureStateless(distinctId, event, properties, options) {
- this.wrap(() => {
- const payload = this.buildPayload({
- distinct_id: distinctId,
- event,
- properties
+ return {
+ stringValue: sanitizeString(String(value))
+ };
+}
+function encodeArrayValues(values, logger, state, depth) {
+ const result = [];
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ let index = 0;
+ for (;index < itemCount && state.remainingNodes > 0; index++)
+ try {
+ const element = index in values ? values[index] : undefined;
+ if (isNullish(element))
+ continue;
+ result.push(encodeAnyValue(element, logger, state, depth));
+ } catch {
+ result.push({
+ stringValue: UNSERIALIZABLE_VALUE
});
- this.enqueue("capture", payload, options);
+ }
+ if (values.length > index)
+ result.push({
+ stringValue: TRUNCATED_VALUE
});
+ return result;
+}
+function encodeKeyValueList(attrs, logger, state, depth) {
+ const result = [];
+ for (const key in attrs)
+ if (propertyIsEnumerable.call(attrs, key)) {
+ if (!key) {
+ logger?.debug("Dropping an attribute with an empty key");
+ continue;
+ }
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
+ logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
+ break;
+ }
+ try {
+ const value = attrs[key];
+ if (isNull(value) || isUndefined(value))
+ continue;
+ result.push({
+ key: sanitizeString(key),
+ value: encodeAnyValue(value, logger, state, depth)
+ });
+ } catch {
+ result.push({
+ key: sanitizeString(key),
+ value: {
+ stringValue: UNSERIALIZABLE_VALUE
+ }
+ });
+ }
+ }
+ return result;
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-resource.mjs
+function buildOtlpResourceAttributes(config, sdkName, sdkVersion) {
+ return {
+ ...assignUserAttributes({}, config.resourceAttributes),
+ "service.name": config.serviceName || "unknown_service",
+ ...config.environment && {
+ "deployment.environment": config.environment
+ },
+ ...config.serviceVersion && {
+ "service.version": config.serviceVersion
+ },
+ "telemetry.sdk.name": sdkName,
+ "telemetry.sdk.version": sdkVersion
+ };
+}
+var SDK_RESOURCE_KEYS = [
+ "service.name",
+ "deployment.environment",
+ "service.version",
+ "telemetry.sdk.name",
+ "telemetry.sdk.version"
+];
+function toOtlpResourceKeyValueList(attributes, logger) {
+ const user = assignUserAttributes({}, attributes);
+ const sdk = {};
+ for (const key of SDK_RESOURCE_KEYS)
+ if (Object.prototype.hasOwnProperty.call(user, key)) {
+ sdk[key] = user[key];
+ delete user[key];
+ }
+ return [
+ ...toOtlpKeyValueList(user, logger),
+ ...toOtlpKeyValueList(sdk, logger)
+ ];
+}
+var OS_NAMES = {
+ darwin: "macOS",
+ win32: "Windows",
+ cygwin: "Windows",
+ linux: "Linux",
+ android: "Android",
+ freebsd: "FreeBSD",
+ openbsd: "OpenBSD",
+ netbsd: "NetBSD",
+ sunos: "SunOS",
+ aix: "AIX",
+ haiku: "Haiku",
+ "Mac OS X": "macOS"
+};
+function normalizeOsName(name) {
+ if (!name)
+ return;
+ return Object.prototype.hasOwnProperty.call(OS_NAMES, name) ? OS_NAMES[name] : name;
+}
+function osResourceAttributes(name, version) {
+ const osName = normalizeOsName(name);
+ return {
+ ...osName ? {
+ "os.name": osName
+ } : {},
+ ...version ? {
+ "os.version": version
+ } : {}
+ };
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
+var OTLP_SEVERITY_MAP = {
+ trace: {
+ text: "TRACE",
+ number: 1
+ },
+ debug: {
+ text: "DEBUG",
+ number: 5
+ },
+ info: {
+ text: "INFO",
+ number: 9
+ },
+ warn: {
+ text: "WARN",
+ number: 13
+ },
+ error: {
+ text: "ERROR",
+ number: 17
+ },
+ fatal: {
+ text: "FATAL",
+ number: 21
}
- async captureStatelessImmediate(distinctId, event, properties, options) {
- const payload = this.buildPayload({
- distinct_id: distinctId,
- event,
- properties
- });
- await this.sendImmediate("capture", payload, options);
+};
+var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/flush-timer.mjs
+class FlushTimer {
+ constructor(_onFire) {
+ this._onFire = _onFire;
+ this._firesAt = 0;
+ }
+ get pending() {
+ return !!this._timer;
+ }
+ arm(delayMs) {
+ this.clear();
+ this._firesAt = Date.now() + delayMs;
+ this._timer = safeSetTimeout(() => {
+ this._timer = undefined;
+ this._onFire();
+ }, delayMs);
+ }
+ armNoEarlierThan(delayMs) {
+ if (this._timer && Date.now() + delayMs <= this._firesAt)
+ return;
+ this.arm(delayMs);
}
- aliasStateless(alias, distinctId, properties, options) {
- this.wrap(() => {
- const payload = this.buildPayload({
- event: "$create_alias",
- distinct_id: distinctId,
- properties: {
- ...properties || {},
- distinct_id: distinctId,
- alias
- }
- });
- this.enqueue("alias", payload, options);
- });
+ clear() {
+ if (this._timer) {
+ clearTimeout(this._timer);
+ this._timer = undefined;
+ }
}
- async aliasStatelessImmediate(alias, distinctId, properties, options) {
- const payload = this.buildPayload({
- event: "$create_alias",
- distinct_id: distinctId,
- properties: {
- ...properties || {},
- distinct_id: distinctId,
- alias
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/backoff.mjs
+var MAX_FLUSH_BACKOFF_EXPONENT = 6;
+var MAX_FLUSH_BACKOFF_MS = 30000;
+var JITTER = 0.25;
+function drawJitter() {
+ return 1 - JITTER + Math.random() * JITTER * 2;
+}
+var NO_JITTER = 1;
+function backoffDelayMs(baseMs, failures, jitter, maxMs) {
+ const exponent = Math.min(Math.max(0, failures - 1), MAX_FLUSH_BACKOFF_EXPONENT);
+ const delay = baseMs * 2 ** exponent;
+ const capped = maxMs === undefined ? delay : Math.min(delay, Math.max(maxMs, baseMs));
+ return Math.round(capped * jitter);
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
+var DEFAULT_HISTOGRAM_BOUNDS = [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 75,
+ 100,
+ 250,
+ 500,
+ 750,
+ 1000,
+ 2500,
+ 5000,
+ 7500,
+ 1e4
+];
+function msToUnixNano(ms) {
+ return String(ms) + "000000";
+}
+function seriesKey(type, name, unit, attributes) {
+ let attrsKey = "";
+ if (attributes) {
+ const keys = Object.keys(attributes).sort();
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
+ }
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
+}
+function bucketIndexFor(value, bounds) {
+ for (let i = 0;i < bounds.length; i++)
+ if (value <= bounds[i])
+ return i;
+ return bounds.length;
+}
+function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
+ return buildOtlpResourceAttributes(config, scopeName, scopeVersion);
+}
+function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
+ return {
+ resourceMetrics: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes)
+ },
+ scopeMetrics: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ metrics
+ }
+ ]
}
+ ]
+ };
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
+var DEFAULT_FLUSH_INTERVAL_MS = 1e4;
+var DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
+function resolveMetricsConfig(config) {
+ const resourceAttributes = config?.resourceAttributes;
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSend: config?.beforeSend,
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
+ };
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
+var OTLP_TEMPORALITY_DELTA = 1;
+
+class PostHogMetrics {
+ constructor(_instance, _config, _logger) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._series = new Map;
+ this._flushTimer = new FlushTimer(() => this.flush().catch((e) => {
+ this._logger.error("Metrics flush failed:", e);
+ }));
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ this._retryAfter = new RetryAfterWindow;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._generation = 0;
+ }
+ count(name, value = 1, options) {
+ this._capture({
+ name,
+ type: "count",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
});
- await this.sendImmediate("alias", payload, options);
}
- groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
- this.wrap(() => {
- const payload = this.buildPayload({
- distinct_id: distinctId || `$${groupType}_${groupKey}`,
- event: "$groupidentify",
- properties: {
- $group_type: groupType,
- $group_key: groupKey,
- $group_set: groupProperties || {},
- ...eventProperties || {}
- }
- });
- this.enqueue("capture", payload, options);
+ gauge(name, value, options) {
+ this._capture({
+ name,
+ type: "gauge",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
});
}
- async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
- const payload = this.buildPayload({
- distinct_id: distinctId || `$${groupType}_${groupKey}`,
- event: "$groupidentify",
- properties: {
- $group_type: groupType,
- $group_key: groupKey,
- $group_set: groupProperties || {},
- ...eventProperties || {}
- }
+ histogram(name, value, options) {
+ this._capture({
+ name,
+ type: "histogram",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
});
- await this.sendImmediate("capture", payload, options);
}
- async getRemoteConfig() {
- await this._initPromise;
- let host = this.host;
- if (host === "https://us.i.posthog.com")
- host = "https://us-assets.i.posthog.com";
- else if (host === "https://eu.i.posthog.com")
- host = "https://eu-assets.i.posthog.com";
- const url = `${host}/array/${this.apiKey}/config`;
- const fetchOptions = {
- method: "GET",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json"
- }
+ flush() {
+ const prev = this._flushPromise;
+ const run = async () => {
+ if (prev)
+ await prev.catch(() => {});
+ await this._doFlush();
};
- return this.fetchWithRetry(url, fetchOptions, {
- type: "required",
- consume: (response) => response.json()
- }, {
- retryCount: 0
- }, this.remoteConfigRequestTimeoutMs).catch((error) => {
- this._logger.error("Remote config could not be loaded", error);
- this._events.emit("error", error);
+ const p = run().finally(() => {
+ if (this._flushPromise === p)
+ this._flushPromise = null;
});
+ this._flushPromise = p;
+ return p;
}
- async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {
- await this._initPromise;
- const configParam = fetchConfig ? "&config=true" : "";
- const url = `${this.host}/flags/?v=2${configParam}`;
- const requestData = {
- token: this.apiKey,
- distinct_id: distinctId,
- groups,
- person_properties: personProperties,
- group_properties: groupProperties,
- ...extraPayload
- };
- if (personProperties.$device_id)
- requestData.$device_id = personProperties.$device_id;
- if (this.evaluationContexts && this.evaluationContexts.length > 0)
- requestData.evaluation_contexts = this.evaluationContexts;
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json"
- },
- body: JSON.stringify(requestData)
- };
- this._logger.info("Flags URL", url);
- return this.fetchWithRetry(url, fetchOptions, {
- type: "required",
- consume: (response) => response.json()
- }, {
- retryCount: this.featureFlagsRequestMaxRetries,
- retryCheck: isRetryableFlagsFetchError
- }, this.featureFlagsRequestTimeoutMs).then((response) => ({
- success: true,
- response: normalizeFlagsResponse(response)
- })).catch((error) => {
- this._events.emit("error", error);
- return {
- success: false,
- error: this.categorizeRequestError(error)
- };
- });
+ drainWindow() {
+ if (this._series.size === 0)
+ return null;
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ return this._buildPayload(window);
}
- categorizeRequestError(error) {
- if (error instanceof PostHogFetchHttpError)
- return {
- type: "api_error",
- statusCode: error.status
- };
- if (error instanceof PostHogFetchNetworkError) {
- const cause = error.error;
- if (cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError"))
- return {
- type: "timeout"
- };
- return {
- type: "connection_error"
+ reset() {
+ this._generation++;
+ this._retryAfter.reset();
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._flushTimer.clear();
+ this._series = new Map;
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ }
+ _capture(sample) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return;
+ const filtered = this._runBeforeSend(sample);
+ if (filtered === null)
+ return;
+ if (!filtered.name || typeof filtered.name != "string")
+ return void this._logger.warn("Dropping metric with empty name");
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
+ if (filtered.type === "count" && filtered.value < 0)
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
+ let attributes;
+ let key;
+ try {
+ attributes = filtered.attributes ? {
+ ...filtered.attributes
+ } : undefined;
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
+ } catch (e) {
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
+ return;
+ }
+ let state = this._series.get(key);
+ if (!state) {
+ if (!this._admitNewSeries())
+ return;
+ state = {
+ name: filtered.name,
+ type: filtered.type,
+ unit: filtered.unit,
+ attributes,
+ windowStartMs: Date.now()
};
+ this._series.set(key, state);
}
- return {
- type: "unknown_error"
- };
+ const seenType = this._typeByName.get(filtered.name);
+ if (seenType === undefined)
+ this._typeByName.set(filtered.name, filtered.type);
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
+ this._typeCollisionWarned.add(filtered.name);
+ this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
+ }
+ this._fold(state, filtered.value);
+ this._armFlushTimer();
}
- async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
- await this._initPromise;
- const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
- if (flagDetailResponse === undefined)
- return {
- response: undefined,
- requestId: undefined
- };
- let response = getFeatureFlagValue(flagDetailResponse.response);
- if (response === undefined)
- response = false;
- return {
- response,
- requestId: flagDetailResponse.requestId
- };
+ _admitNewSeries() {
+ if (this._series.size < this._config.maxSeriesPerFlush)
+ return true;
+ if (!this._seriesCapWarned) {
+ this._seriesCapWarned = true;
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
+ }
+ return false;
}
- async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
- await this._initPromise;
- const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
- key
- ]);
- if (flagsResponse === undefined)
- return;
- const featureFlags = flagsResponse.flags;
- const flagDetail = featureFlags[key];
- return {
- response: flagDetail,
- requestId: flagsResponse.requestId,
- evaluatedAt: flagsResponse.evaluatedAt
- };
+ _fold(state, value) {
+ switch (state.type) {
+ case "count":
+ state.total = (state.total ?? 0) + value;
+ break;
+ case "gauge":
+ state.last = value;
+ break;
+ case "histogram": {
+ if (!state.hist)
+ state.hist = {
+ count: 0,
+ sum: 0,
+ min: value,
+ max: value,
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
+ };
+ const hist = state.hist;
+ hist.count += 1;
+ hist.sum += value;
+ hist.min = Math.min(hist.min, value);
+ hist.max = Math.max(hist.max, value);
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
+ break;
+ }
+ }
+ }
+ _runBeforeSend(sample) {
+ const beforeSend = this._config.beforeSend;
+ if (!beforeSend)
+ return sample;
+ const fns = isArray(beforeSend) ? beforeSend : [
+ beforeSend
+ ];
+ let result = sample;
+ for (const fn of fns)
+ try {
+ const next = fn(result);
+ if (!next) {
+ this._logger.info("Metric was rejected in beforeSend function");
+ return null;
+ }
+ result = next;
+ } catch (e) {
+ this._logger.error("Error in beforeSend function for metric:", e);
+ return null;
+ }
+ return result;
}
- async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
- await this._initPromise;
- const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
- key
- ]);
- if (!payloads)
+ _armFlushTimer() {
+ if (this._flushTimer.pending)
return;
- const response = payloads[key];
- if (response === undefined)
- return null;
- return response;
- }
- async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
- return payloads;
- }
- async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
+ this._flushTimer.arm(this._nextFlushDelay());
}
- async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
- if (!featureFlagDetails)
- return {
- flags: undefined,
- payloads: undefined,
- requestId: undefined
- };
- return {
- flags: featureFlagDetails.featureFlags,
- payloads: featureFlagDetails.featureFlagPayloads,
- requestId: featureFlagDetails.requestId
- };
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
}
- async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- const extraPayload = {
- geoip_disable: disableGeoip ?? this.disableGeoip
- };
- if (flagKeysToEvaluate)
- extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
- const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
- if (!result.success)
+ async _doFlush() {
+ this._flushTimer.clear();
+ if (this._series.size === 0)
return;
- const flagsResponse = result.response;
- if (flagsResponse.errorsWhileComputingFlags)
- console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");
- if (flagsResponse.quotaLimited?.includes("feature_flags")) {
- console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
- return {
- flags: {},
- featureFlags: {},
- featureFlagPayloads: {},
- requestId: flagsResponse?.requestId,
- quotaLimited: flagsResponse.quotaLimited
- };
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ const generation = this._generation;
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
+ if (generation !== this._generation)
+ return;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ } else {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ }
+ if (this._flushTimer.pending)
+ this._flushTimer.arm(this._nextFlushDelay());
+ switch (outcome.kind) {
+ case "ok":
+ return;
+ case "retry-later":
+ this._mergeWindowBack(window);
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ return;
+ case "too-large":
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
+ return;
+ case "fatal":
+ this._logger.error("Failed to send metrics batch:", outcome.error);
+ return;
}
- return flagsResponse;
}
- async getSurveysStateless() {
- await this._initPromise;
- if (this.disabled)
- return [];
- if (this.disableSurveys === true) {
- this._logger.info("Loading surveys is disabled.");
- return [];
+ _buildPayload(window) {
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
+ }
+ _buildMetrics(window) {
+ const nowNano = msToUnixNano(Date.now());
+ const byMetric = new Map;
+ for (const state of window.values()) {
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
+ let metric = byMetric.get(metricKey);
+ if (!metric) {
+ metric = {
+ name: state.name,
+ ...state.unit && {
+ unit: state.unit
+ }
+ };
+ if (state.type === "count")
+ metric.sum = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ isMonotonic: true,
+ dataPoints: []
+ };
+ else if (state.type === "gauge")
+ metric.gauge = {
+ dataPoints: []
+ };
+ else
+ metric.histogram = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ dataPoints: []
+ };
+ byMetric.set(metricKey, metric);
+ }
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
+ const startNano = msToUnixNano(state.windowStartMs);
+ if (state.type === "count") {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ asDouble: state.total ?? 0
+ };
+ metric.sum.dataPoints.push(dp);
+ } else if (state.type === "gauge") {
+ const dp = {
+ attributes,
+ timeUnixNano: nowNano,
+ asDouble: state.last ?? 0
+ };
+ metric.gauge.dataPoints.push(dp);
+ } else if (state.hist) {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ count: state.hist.count,
+ sum: state.hist.sum,
+ min: state.hist.min,
+ max: state.hist.max,
+ bucketCounts: state.hist.bucketCounts,
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
+ };
+ metric.histogram.dataPoints.push(dp);
+ }
}
- const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
- const fetchOptions = {
- method: "GET",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json"
+ return Array.from(byMetric.values());
+ }
+ _mergeWindowBack(window) {
+ for (const [key, old] of window) {
+ const current = this._series.get(key);
+ if (!current) {
+ if (this._admitNewSeries())
+ this._series.set(key, old);
+ continue;
}
- };
- const response = await this.fetchWithRetry(url, fetchOptions, {
- type: "required",
- consume: (response) => {
- if (response.status !== 200 || !response.json) {
- const msg = `Surveys API could not be loaded: ${response.status}`;
- const error = new Error(msg);
- this._logger.error(error);
- this._events.emit("error", new Error(msg));
- return Promise.resolve(undefined);
- }
- return response.json();
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
+ switch (current.type) {
+ case "count":
+ current.total = (current.total ?? 0) + (old.total ?? 0);
+ break;
+ case "gauge":
+ break;
+ case "histogram":
+ if (old.hist)
+ if (current.hist) {
+ current.hist.count += old.hist.count;
+ current.hist.sum += old.hist.sum;
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
+ } else
+ current.hist = old.hist;
+ break;
}
- }).catch((error) => {
- this._logger.error("Surveys API could not be loaded", error);
- this._events.emit("error", error);
- });
- const newSurveys = response?.surveys;
- if (newSurveys)
- this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
- return newSurveys ?? [];
+ }
}
- get props() {
- if (!this._props)
- this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
- return this._props || {};
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/ids.mjs
+var TRACE_ID_BYTES = 16;
+var SPAN_ID_BYTES = 8;
+var TRACE_ID_HEX = 2 * TRACE_ID_BYTES;
+var SPAN_ID_HEX = 2 * SPAN_ID_BYTES;
+var INVALID_TRACE_ID = "0".repeat(TRACE_ID_HEX);
+var INVALID_SPAN_ID = "0".repeat(SPAN_ID_HEX);
+var HEX_RE = /^[0-9a-f]+$/;
+function getRandomBytes(byteLength) {
+ const bytes = new Uint8Array(byteLength);
+ const cryptoLike = globalThis.crypto;
+ if (cryptoLike && typeof cryptoLike.getRandomValues == "function")
+ try {
+ cryptoLike.getRandomValues(bytes);
+ return bytes;
+ } catch {}
+ for (let i = 0;i < byteLength; i++)
+ bytes[i] = Math.floor(256 * Math.random());
+ return bytes;
+}
+function bytesToHex(bytes) {
+ let hex = "";
+ for (let i = 0;i < bytes.length; i++)
+ hex += bytes[i].toString(16).padStart(2, "0");
+ return hex;
+}
+function randomHexId(byteLength) {
+ const hex = bytesToHex(getRandomBytes(byteLength));
+ return /[^0]/.test(hex) ? hex : hex.slice(0, -1) + "1";
+}
+function newTraceId() {
+ return randomHexId(TRACE_ID_BYTES);
+}
+function newSpanId() {
+ return randomHexId(SPAN_ID_BYTES);
+}
+function isValidHexId(value, length, invalid) {
+ return typeof value == "string" && value.length === length && value !== invalid && HEX_RE.test(value);
+}
+function isValidTraceId(value) {
+ return isValidHexId(value, TRACE_ID_HEX, INVALID_TRACE_ID);
+}
+function isValidSpanId(value) {
+ return isValidHexId(value, SPAN_ID_HEX, INVALID_SPAN_ID);
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/traceparent.mjs
+var TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
+function parseTraceparent(value) {
+ const fields = matchTraceparent(value);
+ return fields && {
+ traceId: fields.traceId,
+ spanId: fields.spanId,
+ flags: definedFlags(fields.flags)
+ };
+}
+function definedFlags(flags) {
+ return 1 & parseInt(flags, 16) ? TRACE_FLAGS_SAMPLED : TRACE_FLAGS_UNSAMPLED;
+}
+function matchTraceparent(value) {
+ if (typeof value != "string")
+ return;
+ const match = TRACEPARENT_RE.exec(value.trim());
+ if (!match)
+ return;
+ const [, version, traceId, spanId, flags, trailing] = match;
+ if (version === "ff")
+ return;
+ if (version === "00" && trailing)
+ return;
+ if (!isValidTraceId(traceId) || !isValidSpanId(spanId))
+ return;
+ return {
+ version,
+ traceId,
+ spanId,
+ flags
+ };
+}
+function normalizeTraceparent(value) {
+ return matchTraceparent(value) && value.trim();
+}
+function traceparentHeader(value) {
+ return Array.isArray(value) && value.length === 1 ? value[0] : value;
+}
+var TRACE_FLAGS_SAMPLED = "01";
+var TRACE_FLAGS_UNSAMPLED = "00";
+function formatTraceparent(traceId, spanId, flags = TRACE_FLAGS_SAMPLED) {
+ return `00-${traceId}-${spanId}-${flags}`;
+}
+var TRACESTATE_MAX_MEMBERS = 32;
+var TRACESTATE_MAX_LENGTH = 512;
+function sanitizeTracestate(value) {
+ if (typeof value != "string")
+ return;
+ const trimmed = value.trim();
+ if (!trimmed)
+ return;
+ if (/[^\x20-\x7e\t]/.test(trimmed))
+ return;
+ const members = trimmed.split(",");
+ if (members.length > TRACESTATE_MAX_MEMBERS)
+ return;
+ for (const member of members)
+ if (member.trim() && !member.includes("="))
+ return;
+ if (trimmed.length <= TRACESTATE_MAX_LENGTH)
+ return trimmed;
+ return trimToLength(members);
+}
+var TRACESTATE_LARGE_MEMBER_LENGTH = 128;
+function trimToLength(members) {
+ const kept = [
+ ...members
+ ];
+ const joinedLength = () => kept.reduce((total, member) => total + member.length, 0) + kept.length - 1;
+ for (let index = kept.length - 1;index >= 0 && joinedLength() > TRACESTATE_MAX_LENGTH; index--)
+ if (kept[index].length > TRACESTATE_LARGE_MEMBER_LENGTH)
+ kept.splice(index, 1);
+ while (kept.length && joinedLength() > TRACESTATE_MAX_LENGTH)
+ kept.pop();
+ return kept.length ? kept.join(",") : undefined;
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/sanitize.mjs
+var FALLBACK_SPAN_NAME = "unknown";
+var MAX_TIMESTAMP_MS = 9223372036854;
+var MIN_TIMESTAMP_MS = 0;
+var DEEP_BACKDATE_WARNING_MS = 86400000;
+function sanitizeName(name, label, maxLength, logger) {
+ if (typeof name == "string" && name.trim())
+ return name.length > maxLength ? name.slice(0, maxLength) : name;
+ logger?.debug(`${label} must be a non-empty string; using "${FALLBACK_SPAN_NAME}"`);
+ return FALLBACK_SPAN_NAME;
+}
+function toEpochMs(value) {
+ if (value == null)
+ return;
+ let ms = value;
+ if (value instanceof Date)
+ try {
+ ms = value.getTime();
+ } catch {
+ return;
+ }
+ if (typeof ms != "number" || !Number.isFinite(ms))
+ return;
+ if (ms < MIN_TIMESTAMP_MS || ms > MAX_TIMESTAMP_MS)
+ return;
+ return ms;
+}
+function resolveStartTime(value, now, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug("Span startTime is out of range or not a valid time; using the current time");
+ return now;
}
- set props(val) {
- this._props = val;
+ if (now - supplied > DEEP_BACKDATE_WARNING_MS)
+ logger?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp");
+ else if (supplied > now)
+ logger?.debug("Span startTime is in the future; the span may export with a zero duration");
+ return supplied;
+}
+function clampEndTime(endTime, startTime) {
+ return endTime < startTime ? startTime : endTime;
+}
+function resolveSuppliedTime(value, derived, label, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug(`Span ${label} is out of range or not a valid time; using the derived time`);
+ return derived;
}
- async register(properties) {
- this.wrap(() => {
- this.props = {
- ...this.props,
- ...properties
+ return supplied;
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/span.mjs
+function monotonicNow() {
+ const perf = globalThis.performance;
+ return typeof perf?.now == "function" ? perf.now() : undefined;
+}
+
+class PostHogSpan {
+ constructor(init, _onEnd, _logger) {
+ this._onEnd = _onEnd;
+ this._logger = _logger;
+ this._events = [];
+ this._ended = false;
+ this._userAttributeCount = 0;
+ this._userEventCount = 0;
+ this._droppedAttributes = 0;
+ this._droppedEvents = 0;
+ this._traceId = init.traceId;
+ this._spanId = init.spanId;
+ this._parentSpanId = init.parentSpanId;
+ this._traceState = init.traceState;
+ this._traceFlags = init.traceFlags ?? TRACE_FLAGS_SAMPLED;
+ this._parentIsRemote = init.parentIsRemote ?? false;
+ this._name = init.name;
+ this._kind = init.kind;
+ this._autoKeys = new Set(init.autoAttributeKeys);
+ this._maxAttributes = init.maxAttributes;
+ this._maxEvents = init.maxEvents;
+ this._maxAttributesPerEvent = init.maxAttributesPerEvent;
+ this._maxAttributeValueLength = init.maxAttributeValueLength;
+ this._attributes = Object.create(null);
+ for (const key of Object.keys(init.attributes))
+ this._writeAttribute(key, init.attributes[key]);
+ this._startMono = init.backdated ? undefined : monotonicNow();
+ this._startTime = init.clockAnchor && this._startMono !== undefined ? init.clockAnchor.wall + (this._startMono - init.clockAnchor.mono) : init.startTime;
+ if (this._startMono !== undefined)
+ this._clockAnchor = init.clockAnchor ?? {
+ wall: this._startTime,
+ mono: this._startMono
};
- this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
- });
- }
- async unregister(property) {
- this.wrap(() => {
- delete this.props[property];
- this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
- });
}
- processBeforeEnqueue(message) {
- return message;
+ _now() {
+ if (this._startMono !== undefined) {
+ const mono = monotonicNow();
+ if (mono !== undefined)
+ return this._startTime + Math.max(0, mono - this._startMono);
+ }
+ return Date.now();
}
- async flushStorage() {}
- getQueueRouteKey(_message) {
- return DEFAULT_QUEUE_ROUTE;
+ _mutable(operation) {
+ if (this._ended) {
+ this._logger?.debug(`Ignoring ${operation} on a span that has already ended`);
+ return false;
+ }
+ return true;
}
- persistedQueueKeyForRoute(_route) {
- return types_PostHogPersistedProperty.Queue;
+ _writeAttribute(key, value) {
+ if (isNullish(value)) {
+ if (key in this._attributes && !this._autoKeys.has(key))
+ this._userAttributeCount--;
+ delete this._attributes[key];
+ return;
+ }
+ if (!this._autoKeys.has(key) && !(key in this._attributes)) {
+ if (this._userAttributeCount >= this._maxAttributes)
+ return void this._droppedAttributes++;
+ this._userAttributeCount++;
+ }
+ this._attributes[key] = truncateAttributeValue(value, this._maxAttributeValueLength);
}
- getActiveQueueRoutes() {
- return [
- DEFAULT_QUEUE_ROUTE
- ];
+ setAttribute(key, value) {
+ if (this._mutable("setAttribute"))
+ this._writeAttribute(key, value);
+ return this;
}
- getRouteQueue(route) {
- return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
+ setAttributes(attributes) {
+ if (this._mutable("setAttributes")) {
+ const safe = assignUserAttributes({}, attributes);
+ for (const key of Object.keys(safe))
+ this._writeAttribute(key, safe[key]);
+ }
+ return this;
}
- enqueue(type, _message, options, explicitRoute) {
- this.wrap(() => {
- if (this.optedOut)
- return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
- let message = this.prepareMessage(_message, options);
- message = this.processBeforeEnqueue(message);
- if (message === null)
- return;
- message = this.normalizeMessage(message);
- const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
- const queue = this.getPersistedProperty(queueKey) || [];
- if (queue.length >= this.maxQueueSize) {
- queue.shift();
- this._logger.warn("Queue is full, the oldest event is dropped.");
+ addEvent(name, attributes, timestamp) {
+ if (this._mutable("addEvent")) {
+ if (this._userEventCount >= this._maxEvents) {
+ this._droppedEvents++;
+ return this;
}
- queue.push({
- message
+ this._userEventCount++;
+ const bounded = attributes && boundAttributes(attributes, this._maxAttributesPerEvent, this._maxAttributeValueLength);
+ this._events.push({
+ name: sanitizeName(name, "Span event name", this._maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(timestamp, this._now(), "event timestamp", this._logger),
+ ...bounded && {
+ attributes: bounded.attributes,
+ ...bounded.dropped && {
+ droppedAttributesCount: bounded.dropped
+ }
+ }
});
- this.setPersistedProperty(queueKey, queue);
- this._events.emit(type, message);
- if (queue.length >= this.flushAt)
- this.flushBackground();
- if (this.flushInterval && !this._flushTimer)
- this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
- });
- }
- async sendImmediate(type, _message, options, explicitRoute) {
- if (this.disabled)
- return void this._logger.warn("The client is disabled");
- if (!this._isInitialized)
- await this._initPromise;
- if (this.optedOut)
- return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
- let message = this.prepareMessage(_message, options);
- message = this.processBeforeEnqueue(message);
- if (message === null)
- return;
- message = this.normalizeMessage(message);
- try {
- await this.sendBatch([
- message
- ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
- } catch (err) {
- this._events.emit("error", err);
}
+ return this;
}
- normalizeMessage(message) {
- const { type: _type, library, library_version, ...sanitizedMessage } = message;
- let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
- if (library !== undefined && properties?.$lib === undefined)
- properties = {
- ...properties || {},
- $lib: library
- };
- if (library_version !== undefined && properties?.$lib_version === undefined)
- properties = {
- ...properties || {},
- $lib_version: library_version
+ setStatus(status, message) {
+ if (this._mutable("setStatus")) {
+ if (status !== "ok" && status !== "error") {
+ this._logger?.debug(`Ignoring unknown span status "${String(status)}"; expected "ok" or "error"`);
+ return this;
+ }
+ this._status = {
+ code: status,
+ ...message && {
+ message: truncateString(message, this._maxAttributeValueLength)
+ }
};
- if (properties)
- sanitizedMessage.properties = properties;
- sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
- return sanitizedMessage;
- }
- normalizeTimestampForWire(timestamp) {
- const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
- if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
- return timestamp;
- const normalized = parsedTimestamp.toISOString();
- const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
- return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
- }
- prepareMessage(_message, options) {
- const message = {
- ..._message,
- timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
- uuid: getEventUuid(options?.uuid, uuidv7)
- };
- const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
- if (addGeoipDisableProperty) {
- if (!isPostHogEventProperties(message.properties))
- message.properties = {};
- message.properties["$geoip_disable"] = true;
- }
- if (message.distinctId) {
- message.distinct_id = message.distinctId;
- delete message.distinctId;
}
- return message;
+ return this;
}
- clearFlushTimer() {
- if (this._flushTimer) {
- clearTimeout(this._flushTimer);
- this._flushTimer = undefined;
- }
+ get statusIsExplicitlyOk() {
+ return this._status?.code === "ok";
}
- flushBackground() {
- if (this.pendingFlushPromise)
- return;
- this.flush().catch(async (err) => {
- await logFlushError(err);
+ recordException(error) {
+ if (!this._mutable("recordException"))
+ return this;
+ const { type, message, stack } = describeError(error);
+ this.addEvent(EXCEPTION_EVENT_NAME, {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
+ }
});
+ return this.setStatus("error", message);
}
- async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
- const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
- let iteration = 0;
- while (true) {
- const promises = this.promiseQueue.getPromises([
- ...ignoredPendingPromises,
- ...this.flushPromises
- ], maxPromiseId);
- if (promises.length === 0)
- return;
- if (iteration > 0)
- this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
- await Promise.all(promises.map((promise) => promise.catch(() => {})));
- iteration++;
- }
- }
- flushWithPendingPromises() {
- return this.flushInternal(true);
+ updateName(name) {
+ if (this._mutable("updateName"))
+ this._name = sanitizeName(name, "Span name", this._maxAttributeValueLength, this._logger);
+ return this;
}
- flush() {
- return this.flushInternal(false);
+ traceparent() {
+ return formatTraceparent(this._traceId, this._spanId, this._traceFlags);
}
- flushInternal(waitForPendingPromises) {
- if (this.disabled)
- return Promise.resolve();
- if (!waitForPendingPromises && this.pendingFlushPromise)
- return this.pendingFlushPromise;
- const previousFlushPromise = this.flushPromise;
- const maxPromiseId = this.promiseQueue.maxId;
- const nextFlushPromise = Promise.resolve().then(() => {
- if (waitForPendingPromises)
- return this.waitForPendingPromises(maxPromiseId, [
- previousFlushPromise,
- nextFlushPromise
- ]);
- }).then(() => allSettled([
- previousFlushPromise
- ])).then(() => {
- if (this.pendingFlushPromise === nextFlushPromise)
- this.pendingFlushPromise = null;
- return this._flush();
- });
- this.pendingFlushPromise = nextFlushPromise;
- this.flushPromise = nextFlushPromise;
- this.flushPromises.add(nextFlushPromise);
- this.addPendingPromise(nextFlushPromise);
- allSettled([
- nextFlushPromise
- ]).then(() => {
- this.flushPromises.delete(nextFlushPromise);
- if (this.pendingFlushPromise === nextFlushPromise)
- this.pendingFlushPromise = null;
- if (this.flushPromise === nextFlushPromise)
- this.flushPromise = null;
- });
- return nextFlushPromise;
+ tracestate() {
+ return this._traceState ?? null;
}
- getCustomHeaders() {
- const customUserAgent = this.getCustomUserAgent();
- const headers = {};
- if (customUserAgent && customUserAgent !== "")
- headers["User-Agent"] = customUserAgent;
- return headers;
+ childContext() {
+ return {
+ traceId: this._traceId,
+ parentSpanId: this._spanId,
+ traceState: this._traceState,
+ traceFlags: this._traceFlags,
+ clockAnchor: this._clockAnchor
+ };
}
- compressPayload(payload) {
- return gzipCompress(payload, this.isDebug);
+ end(endTime) {
+ if (this._ended)
+ return void this._logger?.debug("Ignoring end() on a span that has already ended");
+ this._ended = true;
+ const derived = this._now();
+ const resolved = resolveSuppliedTime(endTime, derived, "end time", this._logger);
+ this._onEnd({
+ traceId: this._traceId,
+ spanId: this._spanId,
+ ...this._parentSpanId && {
+ parentSpanId: this._parentSpanId
+ },
+ ...this._traceState && {
+ traceState: this._traceState
+ },
+ traceFlags: this._traceFlags,
+ parentIsRemote: this._parentIsRemote,
+ name: this._name,
+ kind: this._kind,
+ ...this._status && {
+ status: this._status
+ },
+ attributes: {
+ ...this._attributes
+ },
+ events: this._events,
+ startTime: this._startTime,
+ endTime: clampEndTime(resolved, this._startTime),
+ ...this._droppedAttributes && {
+ droppedAttributesCount: this._droppedAttributes
+ },
+ ...this._droppedEvents && {
+ droppedEventsCount: this._droppedEvents
+ }
+ }, this._autoKeys);
}
- getBatchEndpointPath(_route) {
- return "/batch/";
+}
+var EXCEPTION_EVENT_NAME = "exception";
+var MAX_UINT32 = 4294967295;
+function safeString(value) {
+ try {
+ return typeof value == "string" ? value : String(value);
+ } catch {
+ return UNSERIALIZABLE_VALUE;
}
- async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
- const data = {
- api_key: this.apiKey,
- batch: batchMessages.map((message) => {
- if (!message)
- return message;
- const timestamp = this.normalizeTimestampForWire(message.timestamp);
- return timestamp === message.timestamp ? message : {
- ...message,
- timestamp
- };
- }),
- sent_at: currentISOTime()
- };
- if (this.historicalMigration)
- data.historical_migration = true;
- const payload = safeJsonStringify(data);
- const url = `${this.host}${this.getBatchEndpointPath(route)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
+}
+function nonNegativeCount(value) {
+ if (typeof value != "number" || !Number.isFinite(value) || value <= 0)
+ return 0;
+ return Math.min(Math.floor(value), MAX_UINT32);
+}
+function orderedKeys(attributes, keysBeforeHook) {
+ if (!keysBeforeHook.length)
+ return Object.keys(attributes);
+ const beforeHook = keysBeforeHook.filter((key) => Object.prototype.propertyIsEnumerable.call(attributes, key));
+ const seen = new Set(beforeHook);
+ return [
+ ...beforeHook,
+ ...Object.keys(attributes).filter((key) => !seen.has(key))
+ ];
+}
+function applySpanLimits(record, autoKeys, maxAttributes, maxEvents, maxAttributesPerEvent, maxAttributeValueLength, keysBeforeHook = []) {
+ let kept = 0;
+ let droppedAttributes = 0;
+ const attributes = {};
+ for (const key of orderedKeys(record.attributes, keysBeforeHook)) {
+ const value = record.attributes[key];
+ if (!isNullish(value)) {
+ if (!autoKeys.has(key)) {
+ if (kept >= maxAttributes) {
+ droppedAttributes++;
+ continue;
}
- },
- body: gzippedPayload || payload
+ kept++;
+ }
+ Object.defineProperty(attributes, key, {
+ value: truncateAttributeValue(value, maxAttributeValueLength),
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ }
+ record.attributes = attributes;
+ if (droppedAttributes)
+ record.droppedAttributesCount = nonNegativeCount(record.droppedAttributesCount) + droppedAttributes;
+ let keptEvents = 0;
+ let droppedEvents = 0;
+ const events = [];
+ for (const event of record.events) {
+ if (keptEvents >= maxEvents) {
+ droppedEvents++;
+ continue;
+ }
+ keptEvents++;
+ if (event.attributes) {
+ const bounded = boundAttributes(event.attributes, maxAttributesPerEvent, maxAttributeValueLength);
+ event.attributes = bounded.attributes;
+ if (bounded.dropped)
+ event.droppedAttributesCount = nonNegativeCount(event.droppedAttributesCount) + bounded.dropped;
+ }
+ events.push(event);
+ }
+ record.events = events;
+ if (droppedEvents)
+ record.droppedEventsCount = nonNegativeCount(record.droppedEventsCount) + droppedEvents;
+ if (record.status?.message)
+ record.status = {
+ ...record.status,
+ message: truncateString(safeString(record.status.message), maxAttributeValueLength)
};
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, retryOptions);
+}
+
+class NoopSpan {
+ setAttribute() {
+ return this;
}
- async _flush() {
- this.clearFlushTimer();
- await this._initPromise;
- const routes = this.getActiveQueueRoutes();
- if (!routes.some((route) => this.getRouteQueue(route).length > 0))
- return;
- const sentMessages = [];
- let firstError;
- for (const route of routes)
- try {
- await this._flushRoute(route, sentMessages);
- } catch (err) {
- if (firstError === undefined)
- firstError = err;
- }
- if (firstError !== undefined)
- throw firstError;
- this._events.emit("flush", sentMessages);
+ setAttributes() {
+ return this;
}
- async _flushRoute(route, sentMessages) {
- const queueKey = this.persistedQueueKeyForRoute(route);
- let queue = this.getPersistedProperty(queueKey) || [];
- if (!queue.length)
- return;
- const originalQueueLength = queue.length;
- let sentFromRoute = 0;
- while (queue.length > 0 && sentFromRoute < originalQueueLength) {
- const batchItems = queue.slice(0, this.maxBatchSize);
- const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
- const persistQueueChange = async () => {
- const refreshedQueue = this.getPersistedProperty(queueKey) || [];
- const remainingBatchItems = [
- ...batchItems
- ];
- const newQueue = refreshedQueue.filter((item) => {
- const itemUuid = item.message?.uuid;
- const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
- if (batchItemIndex === -1)
- return true;
- remainingBatchItems.splice(batchItemIndex, 1);
- return false;
- });
- this.setPersistedProperty(queueKey, newQueue);
- queue = newQueue;
- this._dequeuedMessagesCount += batchItems.length;
- await this.flushStorage();
- };
- const retryOptions = {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
+ addEvent() {
+ return this;
+ }
+ setStatus() {
+ return this;
+ }
+ recordException() {
+ return this;
+ }
+ updateName() {
+ return this;
+ }
+ traceparent() {
+ return null;
+ }
+ tracestate() {
+ return null;
+ }
+ end() {}
+}
+var NOOP_SPAN = /* @__PURE__ */ new NoopSpan;
+
+class PassThroughSpan extends NoopSpan {
+ constructor(_traceparent, _tracestate) {
+ super(), this._traceparent = _traceparent, this._tracestate = _tracestate;
+ }
+ traceparent() {
+ return this._traceparent;
+ }
+ tracestate() {
+ return this._tracestate ?? null;
+ }
+}
+function readStack(error) {
+ try {
+ const stack = error.stack;
+ return typeof stack == "string" && stack ? {
+ stack
+ } : {};
+ } catch {
+ return {};
+ }
+}
+function inertSpan(options, active) {
+ const parent = traceparentHeader(options?.parent) ?? active;
+ const inbound = typeof parent == "string" || parent == null ? parent : readHandle(parent, "traceparent");
+ const traceparent = normalizeTraceparent(inbound);
+ if (!traceparent)
+ return NOOP_SPAN;
+ const tracestate = typeof parent == "string" || parent == null ? options?.tracestate : readHandle(parent, "tracestate");
+ return new PassThroughSpan(traceparent, sanitizeTracestate(tracestate));
+}
+function readHandle(parent, method) {
+ try {
+ const fn = parent[method];
+ return typeof fn == "function" ? fn.call(parent) : undefined;
+ } catch {
+ return;
+ }
+}
+function truncateString(value, maxLength) {
+ return value.length > maxLength ? value.slice(0, maxLength) : value;
+}
+function truncateAttributeValue(value, maxLength) {
+ return truncateValue(value, maxLength, {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ }, 0);
+}
+function truncateValue(value, maxLength, state, depth) {
+ if (value === null || typeof value != "object") {
+ if (isNullish(value))
+ return value;
+ if (state.remainingNodes <= 0)
+ return value;
+ state.remainingNodes--;
+ return typeof value == "string" ? truncateString(value, maxLength) : value;
+ }
+ if (state.ancestors.has(value))
+ return CIRCULAR_VALUE;
+ if (state.remainingNodes <= 0 || depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return value;
+ state.remainingNodes--;
+ state.ancestors.add(value);
+ try {
+ if (value instanceof Date)
+ return value;
+ const resolved = resolveToJson(value);
+ if (resolved.selfDescribed)
+ return isNullish(resolved.value) ? String(resolved.value) : truncateValue(resolved.value, maxLength, state, depth + 1);
+ if (isArray(value)) {
+ const walked = Math.min(value.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ const boundedItems = [];
+ for (let index = 0;index < walked; index++)
+ try {
+ boundedItems.push(truncateValue(value[index], maxLength, state, depth + 1));
+ } catch {
+ boundedItems.push(UNSERIALIZABLE_VALUE);
}
- };
+ if (value.length > walked)
+ boundedItems.length = value.length;
+ return boundedItems;
+ }
+ const bounded = {};
+ let emittable = 0;
+ for (const key of Object.keys(value)) {
+ if (emittable >= MAX_JSON_SAFE_VALUE_ITEMS)
+ break;
+ let boundedItem;
try {
- await this.sendBatch(batchMessages, retryOptions, route);
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
- this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
- this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
- continue;
- }
- if (!(err instanceof PostHogFetchNetworkError))
- await persistQueueChange();
- this._events.emit("error", err);
- throw err;
+ boundedItem = truncateValue(value[key], maxLength, state, depth + 1);
+ } catch {
+ boundedItem = UNSERIALIZABLE_VALUE;
}
- await persistQueueChange();
- sentMessages.push(...batchMessages);
- sentFromRoute += batchMessages.length;
+ if (key && !isNullish(boundedItem))
+ emittable++;
+ Object.defineProperty(bounded, key, {
+ value: boundedItem,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
}
+ return bounded;
+ } catch {
+ return value;
+ } finally {
+ state.ancestors.delete(value);
}
- async _sendLogsBatch(payload) {
- if (this.disabled)
+}
+function resolveToJson(value) {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
return {
- kind: "fatal",
- error: new Error("The client is disabled")
+ selfDescribed: true,
+ value: toJSON.call(value)
};
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
+ } catch {}
+ return {
+ selfDescribed: false
+ };
+}
+function boundAttributes(source, max, maxLength) {
+ let keys;
+ try {
+ keys = Object.keys(source);
+ } catch {
+ return {
+ attributes: {},
+ dropped: 0
};
+ }
+ const attributes = {};
+ let kept = 0;
+ let dropped = 0;
+ for (const key of keys) {
+ if (kept >= max) {
+ dropped++;
+ continue;
+ }
+ let value;
try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
- }
+ value = truncateAttributeValue(source[key], maxLength);
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ if (!isNullish(value)) {
+ kept++;
+ Object.defineProperty(attributes, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
});
+ }
+ }
+ return {
+ attributes,
+ dropped
+ };
+}
+function truncateAttributes(attributes, maxLength) {
+ for (const key of Object.keys(attributes))
+ attributes[key] = truncateAttributeValue(attributes[key], maxLength);
+ return attributes;
+}
+function runWithActiveSpan(contextManager, span, fn) {
+ return span === NOOP_SPAN ? fn(span) : contextManager.with(span, () => fn(span));
+}
+function describeError(error) {
+ try {
+ const stack = readStack(error);
+ if (isError(error))
return {
- kind: "ok"
+ type: error.name || "Error",
+ message: error.message || "",
+ ...stack
};
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (err instanceof PostHogFetchNetworkError)
+ if (typeof error == "string")
+ return {
+ type: "string",
+ message: error
+ };
+ if (error && typeof error == "object") {
+ const maybe = error;
+ if (typeof maybe.message == "string")
return {
- kind: "retry-later",
- error: err
+ type: typeof maybe.name == "string" ? maybe.name : "Object",
+ message: maybe.message,
+ ...stack
};
- return {
- kind: "fatal",
- error: err
+ }
+ return {
+ type: typeof error,
+ message: String(error)
+ };
+ } catch {
+ return {
+ type: typeof error,
+ message: ""
+ };
+ }
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/otlp.mjs
+var SPAN_KIND_TO_OTLP = {
+ internal: 1,
+ server: 2,
+ client: 3,
+ producer: 4,
+ consumer: 5
+};
+var SPAN_STATUS_TO_OTLP = {
+ ok: 1,
+ error: 2
+};
+var TRACE_FLAGS_SAMPLED2 = 1;
+var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE = 256;
+var SPAN_FLAGS_CONTEXT_IS_REMOTE = 512;
+function spanFlags(record) {
+ const traceFlags = parseInt(record.traceFlags, 16);
+ const w3c = Number.isFinite(traceFlags) ? 255 & traceFlags : TRACE_FLAGS_SAMPLED2;
+ return w3c | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE | (record.parentIsRemote ? SPAN_FLAGS_CONTEXT_IS_REMOTE : 0);
+}
+function wireString(value) {
+ if (typeof value == "string")
+ return sanitizeString(value);
+ try {
+ return sanitizeString(String(value));
+ } catch {
+ return UNSERIALIZABLE_VALUE;
+ }
+}
+function spanKindToOtlp(kind) {
+ if (kind && Object.prototype.hasOwnProperty.call(SPAN_KIND_TO_OTLP, kind))
+ return SPAN_KIND_TO_OTLP[kind];
+ return SPAN_KIND_TO_OTLP.internal;
+}
+function msToUnixNanoString(ms) {
+ let whole = Math.floor(ms);
+ let fractionalNanos = Math.round((ms - whole) * 1e6);
+ if (fractionalNanos >= 1e6) {
+ whole += 1;
+ fractionalNanos = 0;
+ }
+ return String(whole) + String(fractionalNanos).padStart(6, "0");
+}
+function toOtlpEvent(event, logger) {
+ const encoded = {
+ name: wireString(event.name),
+ timeUnixNano: msToUnixNanoString(event.timestamp)
+ };
+ if (event.attributes) {
+ const attributes = toOtlpKeyValueList(event.attributes, logger);
+ if (attributes.length)
+ encoded.attributes = attributes;
+ }
+ const dropped = nonNegativeCount(event.droppedAttributesCount);
+ if (dropped)
+ encoded.droppedAttributesCount = dropped;
+ return encoded;
+}
+function buildOtlpSpan(record, logger) {
+ const span = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ name: wireString(record.name),
+ kind: spanKindToOtlp(record.kind),
+ startTimeUnixNano: msToUnixNanoString(record.startTime),
+ endTimeUnixNano: msToUnixNanoString(record.endTime),
+ flags: spanFlags(record)
+ };
+ if (record.parentSpanId)
+ span.parentSpanId = record.parentSpanId;
+ if (record.traceState)
+ span.traceState = wireString(record.traceState);
+ const attributes = toOtlpKeyValueList(record.attributes, logger);
+ if (attributes.length)
+ span.attributes = attributes;
+ if (record.events.length)
+ span.events = record.events.map((event) => toOtlpEvent(event, logger));
+ const droppedAttributes = nonNegativeCount(record.droppedAttributesCount);
+ if (droppedAttributes)
+ span.droppedAttributesCount = droppedAttributes;
+ const droppedEvents = nonNegativeCount(record.droppedEventsCount);
+ if (droppedEvents)
+ span.droppedEventsCount = droppedEvents;
+ if (record.status)
+ span.status = {
+ code: SPAN_STATUS_TO_OTLP[record.status.code],
+ ...record.status.message && {
+ message: wireString(record.status.message)
+ }
+ };
+ return span;
+}
+function buildTracesResourceAttributes(config, sdkName, sdkVersion) {
+ return buildOtlpResourceAttributes(config, sdkName, sdkVersion);
+}
+function buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, logger) {
+ return {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes, logger)
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ spans
+ }
+ ]
+ }
+ ]
+ };
+}
+
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/index.mjs
+var MAX_RETRIES_PER_BATCH = 8;
+function clockNow() {
+ return monotonicNow() ?? Date.now();
+}
+function isOwnSpan(value) {
+ try {
+ return value instanceof PostHogSpan;
+ } catch {
+ return false;
+ }
+}
+function remoteContext(header, tracestate) {
+ const remote = parseTraceparent(header);
+ if (!remote)
+ return;
+ return {
+ traceId: remote.traceId,
+ parentSpanId: remote.spanId,
+ traceState: sanitizeTracestate(tracestate),
+ traceFlags: remote.flags,
+ isRemote: true
+ };
+}
+function looksLikeSpan(value) {
+ try {
+ return typeof value.traceparent == "function";
+ } catch {
+ return false;
+ }
+}
+function isSpanRecordShape(record) {
+ return !!record.attributes && typeof record.attributes == "object" && !Array.isArray(record.attributes) && Array.isArray(record.events) && record.name !== undefined && record.kind !== undefined && record.startTime !== undefined && record.endTime !== undefined;
+}
+function restoreField(record, field, value) {
+ if (record[field] !== value)
+ record[field] = value;
+}
+function withRestoredIdentity(hooked, original) {
+ try {
+ const descriptors = Object.getOwnPropertyDescriptors(hooked);
+ for (const field of [
+ "traceId",
+ "spanId",
+ "parentSpanId",
+ "traceState"
+ ])
+ descriptors[field] = {
+ value: original[field],
+ enumerable: true,
+ writable: true,
+ configurable: true
};
+ return Object.create(Object.getPrototypeOf(hooked), descriptors);
+ } catch {
+ return hooked;
+ }
+}
+
+class PostHogTraces {
+ constructor(_instance, _config, _logger, _getContext, _contextManager, _onSpanQueued) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._getContext = _getContext;
+ this._contextManager = _contextManager;
+ this._onSpanQueued = _onSpanQueued;
+ this._queue = [];
+ this._flushTimer = new FlushTimer(() => this._flushInBackground());
+ this._flushPromise = null;
+ this._droppedSinceWarning = 0;
+ this._lastDropWarningAt = 0;
+ this._dropReasons = new Set;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter = new RetryAfterWindow;
+ this._headBatchFailures = 0;
+ this._headBatchSize = 0;
+ this._headBatchChargeableAt = 0;
+ this._generation = 0;
+ this._liveSpans = new Map;
+ this._maxExportBatchSize = _config.maxExportBatchSize;
+ }
+ startSpan(name, options) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return inertSpan(options, this._contextManager.active());
+ const explicitParent = traceparentHeader(options?.parent);
+ if (explicitParent && typeof explicitParent != "string" && !isOwnSpan(explicitParent)) {
+ if (looksLikeSpan(explicitParent)) {
+ this._logger.debug("Span parent is not a span from this SDK; returning an inert span");
+ return inertSpan(options, this._contextManager.active());
+ }
+ this._logger.debug("Ignoring an unusable span parent");
+ }
+ const parent = this._resolveParent(explicitParent, options);
+ this._evictAgedSpans();
+ if (this._liveSpans.size >= this._config.maxLiveSpans) {
+ this._recordDrop(1, `the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`);
+ return inertSpan(options, this._contextManager.active());
+ }
+ const now = Date.now();
+ const startTime = resolveStartTime(options?.startTime, now, this._logger);
+ const spanId = newSpanId();
+ this._liveSpans.set(spanId, clockNow());
+ const autoAttributes = this._autoContextAttributes();
+ return new PostHogSpan({
+ traceId: parent?.traceId ?? newTraceId(),
+ spanId,
+ parentSpanId: parent?.parentSpanId,
+ traceState: parent?.traceState,
+ traceFlags: parent?.traceFlags,
+ parentIsRemote: parent?.isRemote,
+ name: sanitizeName(name, "Span name", this._config.maxAttributeValueLength, this._logger),
+ kind: options?.kind ?? "internal",
+ attributes: assignUserAttributes({
+ ...autoAttributes
+ }, options?.attributes),
+ autoAttributeKeys: Object.keys(autoAttributes),
+ maxAttributes: this._config.maxAttributesPerSpan,
+ maxEvents: this._config.maxEventsPerSpan,
+ maxAttributesPerEvent: this._config.maxAttributesPerEvent,
+ maxAttributeValueLength: this._config.maxAttributeValueLength,
+ startTime,
+ backdated: startTime !== now,
+ clockAnchor: toEpochMs(options?.startTime) === undefined ? parent?.clockAnchor : undefined
+ }, (record, autoKeys) => this._onSpanEnd(record, autoKeys), this._logger);
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const span = this.startSpan(name, options);
+ try {
+ const result = runWithActiveSpan(this._contextManager, span, fn);
+ if (isPromise(result))
+ return result.then((value) => {
+ span.end();
+ return value;
+ }, (error) => {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
+ });
+ span.end();
+ return result;
+ } catch (error) {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
+ }
+ }
+ getActiveSpan() {
+ return this._contextManager.active() ?? null;
+ }
+ get throttled() {
+ return this._retryAfter.isOpen();
+ }
+ async flush() {
+ for (;; ) {
+ if (!this._queue.length)
+ return;
+ const inFlight = this._flushPromise;
+ const removed = await (inFlight ?? this._startFlush());
+ if (!removed)
+ return;
+ }
+ }
+ _startFlush() {
+ this._flushTimer.clear();
+ const startedAtGeneration = this._generation;
+ const promise = Promise.resolve().then(() => startedAtGeneration === this._generation ? this._flushInner() : 0).finally(() => {
+ if (this._flushPromise === promise)
+ this._flushPromise = null;
+ this._armFlushTimerIfQueuedNoEarlierThan();
+ });
+ this._flushPromise = promise;
+ return promise;
+ }
+ reset() {
+ this._flushTimer.clear();
+ if (this._queue.length)
+ this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`);
+ this._queue = [];
+ this._liveSpans.clear();
+ this._flushPromise = null;
+ this._generation++;
+ this._maxExportBatchSize = this._config.maxExportBatchSize;
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ this._lastDropWarningAt = 0;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter.reset();
+ this._resetHeadBatchBudget();
+ }
+ _resetHeadBatchBudget() {
+ this._headBatchFailures = 0;
+ this._headBatchChargeableAt = 0;
+ }
+ _resolveParent(explicit, options) {
+ if (typeof explicit == "string") {
+ const remote = remoteContext(explicit, options?.tracestate);
+ if (!remote)
+ this._logger.debug("Ignoring malformed traceparent; starting a new trace");
+ return remote;
+ }
+ if (isOwnSpan(explicit))
+ return explicit.childContext();
+ const active = this._contextManager.active();
+ if (isOwnSpan(active))
+ return active.childContext();
+ if (active instanceof PassThroughSpan)
+ return remoteContext(active.traceparent(), active.tracestate() ?? undefined);
+ }
+ _autoContextAttributes() {
+ let context;
+ try {
+ context = this._getContext();
+ } catch (error) {
+ this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes", error);
+ return {};
+ }
+ const attributes = {};
+ if (context.distinctId)
+ attributes.posthogDistinctId = context.distinctId;
+ if (context.sessionId)
+ attributes.sessionId = context.sessionId;
+ if (context.currentUrl)
+ attributes["url.full"] = context.currentUrl;
+ if (context.screenName)
+ attributes["screen.name"] = context.screenName;
+ if (context.appState)
+ attributes["app.state"] = context.appState;
+ return attributes;
+ }
+ _recordCallbackError(span, error) {
+ if (!(span instanceof PostHogSpan))
+ return;
+ const { type, message, stack } = describeError(error);
+ span.addEvent("exception", {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
+ }
+ });
+ if (!span.statusIsExplicitlyOk)
+ span.setStatus("error", message);
+ }
+ _evictAgedSpans() {
+ const cutoff = clockNow() - this._config.maxSpanAgeMs;
+ let evicted = 0;
+ for (const [spanId, startedAt] of this._liveSpans) {
+ if (startedAt > cutoff)
+ break;
+ this._liveSpans.delete(spanId);
+ evicted++;
}
+ if (evicted)
+ this._recordDrop(evicted, `they were still live after ${this._config.maxSpanAgeMs}ms`);
}
- async _sendMetricsBatch(payload) {
- if (this.disabled)
- return {
- kind: "fatal",
- error: new Error("The client is disabled")
- };
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
+ _onSpanEnd(incoming, autoKeys) {
+ if (!this._liveSpans.delete(incoming.spanId))
+ return;
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return void this._recordDrop(1, "the user has opted out");
+ const record = this._runBeforeSpanSend(incoming, autoKeys);
+ if (!record)
+ return;
+ this._reportLimitDrops(record);
+ if (this._queue.length >= this._config.maxQueueSize)
+ return void this._recordDrop(1, `the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);
+ this._queue.push(record);
+ try {
+ this._onSpanQueued?.();
+ } catch (error) {
+ this._logger.debug("Span queue notification failed", error);
+ }
+ if (!(this._queue.length >= this._maxExportBatchSize) || this._consecutiveFlushFailures || this._retryAfter.isOpen())
+ this._armFlushTimerIfQueued();
+ else
+ this._flushInBackground();
+ }
+ _reportLimitDrops(record) {
+ const attributes = record.droppedAttributesCount ?? 0;
+ const events = record.droppedEventsCount ?? 0;
+ let eventAttributes = 0;
+ for (const event of record.events)
+ eventAttributes += event.droppedAttributesCount ?? 0;
+ if (attributes || events || eventAttributes)
+ this._logger.debug(`Span limits discarded data from "${record.name}": ${attributes} attributes, ${events} events, ${eventAttributes} event attributes`);
+ }
+ _runBeforeSpanSend(record, autoKeys) {
+ if (!this._config.beforeSpanSend.length)
+ return record;
+ const identity = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ parentSpanId: record.parentSpanId,
+ traceState: record.traceState
+ };
+ const originalTimes = {
+ startTime: record.startTime,
+ endTime: record.endTime
};
+ const originalDropped = {
+ attributes: record.droppedAttributesCount,
+ events: record.droppedEventsCount
+ };
+ const keysBeforeHook = Object.keys(record.attributes);
+ const originalPropagation = {
+ traceFlags: record.traceFlags,
+ parentIsRemote: record.parentIsRemote
+ };
+ const originalStatus = record.status && {
+ ...record.status
+ };
+ let hooked = record;
+ let current = record;
try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
+ for (const hook of this._config.beforeSpanSend) {
+ const result = hook(hooked);
+ if (!result) {
+ this._recordDrop(1, "beforeSpanSend dropped it");
+ return null;
}
- });
- return {
- kind: "ok"
- };
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (isPostHogFetchRetryableError(err))
- return {
- kind: "retry-later",
- error: err
- };
- return {
- kind: "fatal",
- error: err
+ hooked = this._keepSpanIdentity(result, identity);
+ }
+ const rebuilt = {
+ traceId: identity.traceId,
+ spanId: identity.spanId,
+ parentSpanId: identity.parentSpanId,
+ traceState: identity.traceState,
+ name: hooked.name,
+ kind: hooked.kind,
+ status: hooked.status,
+ attributes: hooked.attributes,
+ events: hooked.events,
+ startTime: hooked.startTime,
+ endTime: hooked.endTime,
+ traceFlags: originalPropagation.traceFlags,
+ parentIsRemote: originalPropagation.parentIsRemote,
+ droppedAttributesCount: originalDropped.attributes,
+ droppedEventsCount: originalDropped.events
};
+ current = rebuilt;
+ if (!isSpanRecordShape(current)) {
+ this._logger.debug("beforeSpanSend did not return a span record; dropping the span");
+ this._recordDrop(1, "beforeSpanSend returned an unusable record");
+ return null;
+ }
+ current.name = sanitizeName(current.name, "Span name", this._config.maxAttributeValueLength, this._logger);
+ if (current.status && current.status.code !== "ok" && current.status.code !== "error") {
+ this._logger.debug("beforeSpanSend set an unknown span status; keeping the original");
+ current.status = originalStatus;
+ }
+ current.startTime = toEpochMs(current.startTime) ?? originalTimes.startTime;
+ current.endTime = clampEndTime(toEpochMs(current.endTime) ?? originalTimes.endTime, current.startTime);
+ const sanitizedEvents = [];
+ for (const event of current.events)
+ try {
+ sanitizedEvents.push({
+ ...event,
+ name: sanitizeName(event.name, "Span event name", this._config.maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(event.timestamp, current.startTime, "event timestamp", this._logger)
+ });
+ } catch {
+ this._logger.debug("beforeSpanSend left an unreadable span event; dropping it");
+ }
+ current.events = sanitizedEvents;
+ applySpanLimits(current, autoKeys, this._config.maxAttributesPerSpan, this._config.maxEventsPerSpan, this._config.maxAttributesPerEvent, this._config.maxAttributeValueLength, keysBeforeHook);
+ return current;
+ } catch (error) {
+ this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed", error);
+ this._recordDrop(1, "beforeSpanSend failed");
+ return null;
}
}
- async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
- const body = options.body ? options.body : "";
- let reqByteLength = -1;
+ _keepSpanIdentity(hooked, original) {
+ if (hooked.traceId !== original.traceId || hooked.spanId !== original.spanId || hooked.parentSpanId !== original.parentSpanId)
+ this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");
try {
- reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
+ restoreField(hooked, "traceId", original.traceId);
+ restoreField(hooked, "spanId", original.spanId);
+ restoreField(hooked, "parentSpanId", original.parentSpanId);
+ restoreField(hooked, "traceState", original.traceState);
} catch {
- if (body instanceof Blob)
- reqByteLength = body.size;
- else if (body instanceof Uint8Array)
- reqByteLength = body.byteLength;
- else {
- const encoded = new TextEncoder().encode(body);
- reqByteLength = encoded.length;
- }
+ return withRestoredIdentity(hooked, original);
}
- const retriableOptions = {
- ...this._retryOptions,
- ...retryOptions
- };
- let attempt = 0;
- return await retriable(async () => {
- attempt++;
- const ctrl = new AbortController;
- const timeoutMs = requestTimeout ?? this.requestTimeout;
- const requestDeadline = Date.now() + timeoutMs;
- let timer;
- const deadline = new Promise((_resolve, reject) => {
- timer = safeSetTimeout(() => {
- const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
- timeoutError.name = "AbortError";
- reject(timeoutError);
- ctrl.abort(timeoutError);
- }, timeoutMs);
- });
- let res;
- let responseAccepted = false;
- let cancellation;
- const cancelBody = () => cancellation ??= (async () => {
- try {
- await res?.body?.cancel();
- } catch {}
- })();
+ return hooked;
+ }
+ _recordDrop(count, reason) {
+ this._droppedSinceWarning += count;
+ this._dropReasons.add(reason);
+ if (Date.now() - this._lastDropWarningAt >= this._config.flushIntervalMs)
+ this._warnAboutDrops();
+ }
+ _warnAboutDrops() {
+ if (!this._droppedSinceWarning)
+ return;
+ this._lastDropWarningAt = Date.now();
+ this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[
+ ...this._dropReasons
+ ].join("; ")}`);
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ }
+ _encodeBatch(batch) {
+ const encoded = [];
+ for (const record of batch)
try {
- let fetchPromise;
- try {
- fetchPromise = this.fetch(url, {
- signal: ctrl.signal,
- ...options
- });
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
+ encoded.push(buildOtlpSpan(record, this._logger));
+ } catch (error) {
+ this._logger.debug("Failed to encode a span; dropping it", error);
+ this._recordDrop(1, "its attributes could not be encoded");
+ }
+ return encoded;
+ }
+ _discardQueueIfConsentWithdrawn() {
+ if (!this._instance.isDisabled && !this._instance.optedOut)
+ return 0;
+ const discarded = this._queue.length;
+ this._queue = [];
+ this._resetHeadBatchBudget();
+ this._recordDrop(discarded, "the user has opted out");
+ this._warnAboutDrops();
+ return discarded;
+ }
+ async _flushInner() {
+ if (!this._queue.length)
+ return 0;
+ const discardedBeforeDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedBeforeDrain)
+ return discardedBeforeDrain;
+ const resourceAttributes = truncateAttributes(buildTracesResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._config.maxAttributeValueLength);
+ const scopeName = this._instance.getLibraryId();
+ const scopeVersion = this._instance.getLibraryVersion();
+ let remaining = this._queue.length;
+ let removed = 0;
+ let localCap = 1 / 0;
+ const generation = this._generation;
+ try {
+ while (remaining > 0 && this._queue.length > 0) {
+ const discardedMidDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedMidDrain)
+ return removed + discardedMidDrain;
+ const cap = this._headBatchFailures > 0 ? Math.min(this._maxExportBatchSize, this._headBatchSize) : this._maxExportBatchSize;
+ const size = Math.max(1, Math.min(cap, localCap, remaining, this._queue.length));
+ const batch = this._queue.slice(0, size);
+ const spans = this._encodeBatch(batch);
+ if (!spans.length) {
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._resetHeadBatchBudget();
+ continue;
}
- fetchPromise.then((lateResponse) => {
- if (ctrl.signal.aborted && !responseAccepted)
- Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
- }).catch(() => {});
- try {
- res = await Promise.race([
- fetchPromise,
- deadline
- ]);
- responseAccepted = true;
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
+ const chargeable = clockNow() >= this._headBatchChargeableAt && !this._retryAfter.isOpen();
+ const outcome = await this._instance._sendTracesBatch(buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, this._logger));
+ if (generation !== this._generation)
+ break;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "ok") {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ if (this._maxExportBatchSize < this._config.maxExportBatchSize)
+ this._maxExportBatchSize++;
+ continue;
}
- const isNoCors = options.mode === "no-cors";
- if (!isNoCors && (res.status < 200 || res.status >= 400))
- throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
- if (responseHandling.type === "successful-write") {
- try {
- await Promise.race([
- cancelBody(),
- deadline
- ]);
- } catch {}
- return;
+ if (outcome.kind === "too-large") {
+ if (size === 1) {
+ this._queue.splice(0, 1);
+ remaining -= 1;
+ removed += 1;
+ this._recordDrop(1, "it is too large for the ingestion endpoint");
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ continue;
+ }
+ const halved = Math.max(1, Math.floor(size / 2));
+ if (outcome.measuredLocally)
+ localCap = halved;
+ else
+ this._maxExportBatchSize = halved;
+ this._resetHeadBatchBudget();
+ this._logger.debug(`Batch too large; retrying the same spans in batches of ${halved}`);
+ continue;
}
- try {
- return await Promise.race([
- responseHandling.consume(res),
- deadline
- ]);
- } catch (e) {
- if (ctrl.signal.aborted)
- throw new PostHogFetchNetworkError(e);
- throw e;
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ this._headBatchSize = size;
+ if (chargeable) {
+ this._headBatchFailures++;
+ this._headBatchChargeableAt = clockNow() + this._nextFlushDelay();
+ }
+ if (this._headBatchFailures < MAX_RETRIES_PER_BATCH) {
+ this._logger.debug("Span export failed; retrying on the next flush", outcome.error);
+ return removed;
+ }
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, `the ingestion endpoint failed ${MAX_RETRIES_PER_BATCH} times in a row`);
+ if (this._retryAfter.isOpen())
+ return removed;
+ continue;
}
- } finally {
- clearTimeout(timer);
- if (ctrl.signal.aborted && res)
- cancelBody();
- }
- }, {
- ...retriableOptions,
- retryCheck: (error) => {
- const shouldRetry = retriableOptions.retryCheck(error);
- if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
- error.cancelResponseBody();
- return shouldRetry;
+ this._logger.debug("Dropping a span batch the ingestion endpoint rejected", outcome.error);
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, "the ingestion endpoint rejected the batch");
}
- });
+ return removed;
+ } finally {
+ this._warnAboutDrops();
+ }
}
- async _shutdown(shutdownTimeoutMs = 30000) {
- await this._initPromise;
- let hasTimedOut = false;
- this.clearFlushTimer();
- if (this.disabled)
+ _flushInBackground() {
+ if (this._backgroundFlush)
return;
- const doShutdown = async () => {
- try {
- await this.promiseQueue.join();
- while (true) {
- const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
- if (!hasQueuedEvents)
- break;
- const dequeuedBeforeFlush = this._dequeuedMessagesCount;
- await this.flush();
- if (hasTimedOut)
- break;
- if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
- this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
- break;
- }
- }
- } catch (e) {
- if (!isPostHogFetchError(e))
- throw e;
- await logFlushError(e);
- }
- };
- return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
- this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
- shutdownTimeoutMs
- });
- hasTimedOut = true;
+ this._backgroundFlush = this.flush().catch((error) => {
+ this._logger.debug("Background span flush failed", error);
+ }).finally(() => {
+ this._backgroundFlush = undefined;
+ this._armFlushTimerIfQueuedNoEarlierThan();
});
}
- async shutdown(shutdownTimeoutMs = 30000) {
- if (this.shutdownPromise)
- this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
- else
- this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
- this.shutdownPromise = null;
- });
- return this.shutdownPromise;
+ _armFlushTimerIfQueued() {
+ if (this._flushTimer.pending || !this._queue.length)
+ return;
+ this._flushTimer.arm(this._nextFlushDelay());
+ }
+ _armFlushTimerIfQueuedNoEarlierThan() {
+ if (!this._queue.length)
+ return;
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ }
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
+ }
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/context.mjs
+class SyncSpanContextManager {
+ active() {
+ return this._active;
+ }
+ with(span, fn) {
+ const previous = this._active;
+ this._active = span;
+ try {
+ return fn();
+ } finally {
+ this._active = previous;
+ }
+ }
+}
+// ../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/config.mjs
+var DEFAULT_FLUSH_INTERVAL_MS2 = 5000;
+var DEFAULT_MAX_EXPORT_BATCH_SIZE = 512;
+var DEFAULT_MAX_QUEUE_SIZE = 2048;
+var DEFAULT_MAX_ATTRIBUTES_PER_SPAN = 128;
+var DEFAULT_MAX_EVENTS_PER_SPAN = 128;
+var DEFAULT_MAX_ATTRIBUTES_PER_EVENT = 128;
+var DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 8192;
+var DEFAULT_MAX_LIVE_SPANS = 1e4;
+var DEFAULT_MAX_SPAN_AGE_MS = 3600000;
+function positiveInteger(value, fallback) {
+ return typeof value == "number" && Number.isInteger(value) && value >= 1 ? value : fallback;
+}
+var IDENTITY_KEYS = [
+ "service.name",
+ "service.version",
+ "deployment.environment"
+];
+function withUsableIdentityKeys(attributes) {
+ if (!attributes || typeof attributes != "object" || Array.isArray(attributes))
+ return;
+ try {
+ if (IDENTITY_KEYS.every((key) => !(key in attributes) || typeof attributes[key] == "string"))
+ return attributes;
+ const usable = {
+ ...attributes
+ };
+ for (const key of IDENTITY_KEYS)
+ if (key in usable && typeof usable[key] != "string")
+ delete usable[key];
+ return usable;
+ } catch {
+ return;
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
+function resolveBeforeSpanSend(beforeSpanSend, logger) {
+ if (!beforeSpanSend)
+ return [];
+ const supplied = [
+ beforeSpanSend
+ ].flat().filter((hook) => Boolean(hook));
+ const hooks = supplied.filter((hook) => typeof hook == "function");
+ if (hooks.length !== supplied.length)
+ logger?.critical(`beforeSpanSend: ignoring ${supplied.length - hooks.length} of ${supplied.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);
+ return hooks;
+}
+function resolveTracesConfig(config, hostResourceAttributes, logger) {
+ const resourceAttributes = assignUserAttributes({
+ ...hostResourceAttributes
+ }, withUsableIdentityKeys(config?.resourceAttributes));
+ const maxExportBatchSize = positiveInteger(config?.maxExportBatchSize, DEFAULT_MAX_EXPORT_BATCH_SIZE);
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSpanSend: resolveBeforeSpanSend(config?.beforeSpanSend, logger),
+ maxAttributesPerSpan: positiveInteger(config?.maxAttributesPerSpan, DEFAULT_MAX_ATTRIBUTES_PER_SPAN),
+ maxEventsPerSpan: positiveInteger(config?.maxEventsPerSpan, DEFAULT_MAX_EVENTS_PER_SPAN),
+ maxAttributesPerEvent: DEFAULT_MAX_ATTRIBUTES_PER_EVENT,
+ maxAttributeValueLength: positiveInteger(config?.maxAttributeValueLength, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH),
+ flushIntervalMs: positiveInteger(config?.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS2),
+ maxExportBatchSize,
+ maxQueueSize: Math.max(positiveInteger(config?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE), maxExportBatchSize),
+ maxLiveSpans: positiveInteger(config?.maxLiveSpans, DEFAULT_MAX_LIVE_SPANS),
+ maxSpanAgeMs: positiveInteger(config?.maxSpanAgeMs, DEFAULT_MAX_SPAN_AGE_MS)
+ };
+}
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
import { constants as constants2 } from "node:fs";
import { open as promises_open } from "node:fs/promises";
import { isAbsolute } from "node:path";
@@ -4133,7 +6532,7 @@ function snipLine(line, colno) {
return newLine;
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
import { isAbsolute as isAbsolute2, relative, sep as sep2 } from "node:path";
function createRelativePathModifier(basePath = process.cwd()) {
const isWindows = sep2 === "\\";
@@ -4149,10 +6548,10 @@ function createRelativePathModifier(basePath = process.cwd()) {
};
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
-var version = "5.51.1";
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
+var version = "5.52.4";
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
var FeatureFlagError2 = {
ERRORS_WHILE_COMPUTING: "errors_while_computing_flags",
FLAG_MISSING: "flag_missing",
@@ -4160,7 +6559,7 @@ var FeatureFlagError2 = {
UNKNOWN_ERROR: "unknown_error"
};
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
class FeatureFlagEvaluations {
constructor(init) {
this._host = init.host;
@@ -4293,23 +6692,8 @@ class FeatureFlagEvaluations {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
-async function hashSHA1(text) {
- const subtle = globalThis.crypto?.subtle;
- if (!subtle)
- throw new Error("SubtleCrypto API not available");
- const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
-}
-
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
-var SIXTY_SECONDS = 60000;
-var LONG_SCALE = 1152921504606847000;
-var NULL_VALUES_ALLOWED_OPERATORS = [
- "is_not",
- "is_set"
-];
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
+var SIXTY_SECONDS = 60000;
class ClientError extends Error {
constructor(message) {
@@ -4326,13 +6710,6 @@ function setCustomErrorPrototype(error, constructor) {
Object.setPrototypeOf(error, constructor.prototype);
}
-class InconclusiveMatchError extends Error {
- constructor(message) {
- super(message);
- setCustomErrorPrototype(this, InconclusiveMatchError);
- }
-}
-
class RequiresServerEvaluation extends Error {
constructor(message) {
super(message);
@@ -4346,6 +6723,7 @@ class FeatureFlagsPoller {
this.shouldBeginExponentialBackoff = false;
this.backOffCount = 0;
this.pollerStopped = false;
+ this.filteredOutFlagKeys = new Set;
this.pollingInterval = pollingInterval;
this.personalApiKey = personalApiKey;
this.featureFlags = [];
@@ -4364,6 +6742,7 @@ class FeatureFlagsPoller {
this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
this.cacheProvider = options.cacheProvider;
this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
+ this.evaluationContexts = options.evaluationContexts;
this.loadFeatureFlags();
}
debug(enabled = true) {
@@ -4495,23 +6874,7 @@ class FeatureFlagsPoller {
return distinctId;
}
getFeatureFlagPayload(key, flagValue) {
- let payload = null;
- if (flagValue !== false && flagValue != null) {
- if (typeof flagValue == "boolean")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
- else if (typeof flagValue == "string")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
- if (payload != null) {
- if (typeof payload == "object")
- return payload;
- if (typeof payload == "string")
- try {
- return JSON.parse(payload);
- } catch {}
- return payload;
- }
- }
- return null;
+ return resolveFeatureFlagPayload(this.featureFlagsByKey?.[key]?.filters?.payloads, flagValue);
}
async evaluateFlagDependency(property, properties, evaluationContext) {
const { evaluationCache } = evaluationContext;
@@ -4538,6 +6901,8 @@ class FeatureFlagsPoller {
}
else
evaluationCache[depFlagKey] = false;
+ else if (this.filteredOutFlagKeys.has(depFlagKey))
+ evaluationCache[depFlagKey] = false;
else
throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
}
@@ -4590,8 +6955,11 @@ class FeatureFlagsPoller {
result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
break;
}
- if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound") {
+ if (isInconclusive)
+ break;
return false;
+ }
} catch (e) {
if (e instanceof RequiresServerEvaluation)
throw e;
@@ -4626,36 +6994,33 @@ class FeatureFlagsPoller {
if (rolloutPercentage == undefined)
return "match";
}
- if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
+ if (rolloutPercentage != null && await getFeatureFlagHash(flag.key, bucketingValue) > rolloutPercentage / 100)
return "out_of_rollout_bound";
return "match";
}
async getMatchingVariant(flag, bucketingValue) {
- const hashValue = await _hash(flag.key, bucketingValue, "variant");
- const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
- if (matchingVariant)
- return matchingVariant.key;
+ return getFeatureFlagVariant(flag.key, bucketingValue, flag.filters?.multivariate?.variants || []);
}
variantLookupTable(flag) {
- const lookupTable = [];
- let valueMin = 0;
- let valueMax = 0;
- const flagFilters = flag.filters || {};
- const multivariates = flagFilters.multivariate?.variants || [];
- multivariates.forEach((variant) => {
- valueMax = valueMin + variant.rollout_percentage / 100;
- lookupTable.push({
- valueMin,
- valueMax,
- key: variant.key
- });
- valueMin = valueMax;
+ return getFeatureFlagVariantLookupTable(flag.filters?.multivariate?.variants || []);
+ }
+ filterFlagsByEvaluationContexts(flags) {
+ if (!this.evaluationContexts || this.evaluationContexts.length === 0)
+ return flags;
+ const contexts = new Set(this.evaluationContexts);
+ return flags.filter((flag) => {
+ const tags = flag.evaluation_contexts ?? flag.evaluation_tags;
+ if (!tags || tags.length === 0)
+ return true;
+ return tags.some((tag) => contexts.has(tag));
});
- return lookupTable;
}
updateFlagState(flagData) {
- this.featureFlags = flagData.flags;
- this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const flags = this.filterFlagsByEvaluationContexts(flagData.flags);
+ this.featureFlags = flags;
+ this.featureFlagsByKey = flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const keptKeys = new Set(flags.map((flag) => flag.key));
+ this.filteredOutFlagKeys = new Set(flagData.flags.filter((flag) => !keptKeys.has(flag.key)).map((flag) => flag.key));
this.groupTypeMapping = flagData.groupTypeMapping;
this.cohorts = flagData.cohorts;
this.loadedSuccessfullyOnce = true;
@@ -4677,7 +7042,7 @@ class FeatureFlagsPoller {
this.updateFlagState(cached);
this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(cached.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
return true;
}
return false;
@@ -4755,6 +7120,7 @@ class FeatureFlagsPoller {
console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
this.featureFlags = [];
this.featureFlagsByKey = {};
+ this.filteredOutFlagKeys = new Set;
this.groupTypeMapping = {};
this.cohorts = {};
this.onMinimalFlagCalledEvents?.(false);
@@ -4786,7 +7152,7 @@ class FeatureFlagsPoller {
this.onError?.(new Error(`Failed to store in cache: ${err}`));
}
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(flagData.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
break;
}
default:
@@ -4872,136 +7238,10 @@ class FeatureFlagsPoller {
}
}
}
-async function _hash(key, bucketingValue, salt = "") {
- const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
- return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
-}
function matchProperty(property, propertyValues, warnFunction) {
- const key = property.key;
- const value = property.value;
- const operator = property.operator || "exact";
- if (key in propertyValues) {
- if (operator === "is_not_set")
- return false;
- } else {
- if (operator === "is_not_set")
- return true;
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
- }
- const overrideValue = propertyValues[key];
- if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
- if (warnFunction)
- warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
- return false;
- }
- function computeExactMatch(value, overrideValue) {
- if (Array.isArray(value))
- return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
- return String(value).toLowerCase() === String(overrideValue).toLowerCase();
- }
- function compare(lhs, rhs, operator) {
- if (operator === "gt")
- return lhs > rhs;
- if (operator === "gte")
- return lhs >= rhs;
- if (operator === "lt")
- return lhs < rhs;
- if (operator === "lte")
- return lhs <= rhs;
- throw new Error(`Invalid operator: ${operator}`);
- }
- switch (operator) {
- case "exact":
- return computeExactMatch(value, overrideValue);
- case "is_not":
- return !computeExactMatch(value, overrideValue);
- case "is_set":
- return key in propertyValues;
- case "icontains":
- return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "not_icontains":
- return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "starts_with":
- return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "not_starts_with":
- return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "ends_with":
- return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "not_ends_with":
- return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
- case "not_regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
- case "gt":
- case "gte":
- case "lt":
- case "lte": {
- const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
- let parsedOverride;
- parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : NaN;
- if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
- return compare(parsedOverride, parsedValue, operator);
- return compare(String(overrideValue), String(value), operator);
- }
- case "is_date_after":
- case "is_date_before": {
- if (typeof value == "boolean")
- throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
- if (parsedDate == null)
- parsedDate = convertToDateTime(value);
- if (parsedDate == null)
- throw new InconclusiveMatchError(`Invalid date: ${value}`);
- const overrideDate = convertToDateTime(overrideValue);
- if ([
- "is_date_before"
- ].includes(operator))
- return overrideDate < parsedDate;
- return overrideDate > parsedDate;
- }
- case "semver_eq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp === 0;
- }
- case "semver_neq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp !== 0;
- }
- case "semver_gt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp > 0;
- }
- case "semver_gte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp >= 0;
- }
- case "semver_lt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp < 0;
- }
- case "semver_lte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp <= 0;
- }
- case "semver_tilde": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeTildeBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_caret": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeCaretBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_wildcard": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeWildcardBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- default:
- throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
- }
+ return matchFeatureFlagProperty(property, propertyValues, {
+ warnFunction
+ });
}
function checkCohortExists(cohortId, cohortProperties) {
if (!(cohortId in cohortProperties))
@@ -5081,181 +7321,8 @@ async function matchPropertyGroup(propertyGroup, propertyValues, cohortPropertie
throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
return propertyGroupType === "AND";
}
-function isValidRegex(regex) {
- try {
- new RegExp(regex);
- return true;
- } catch (err) {
- return false;
- }
-}
-function parseSemverNumericIdentifier(part, raw) {
- if (!/^\d+$/.test(part))
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- if (part.length > 1 && part[0] === "0")
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- return parseInt(part, 10);
-}
-function parseSemver(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const baseVersion = text.split("-")[0].split("+")[0];
- if (!baseVersion || baseVersion.startsWith("."))
- throw new InconclusiveMatchError(`Invalid semver: ${value}`);
- const parts = baseVersion.split(".");
- const parsePart = (part) => {
- if (part === undefined || part === "")
- return 0;
- return parseSemverNumericIdentifier(part, value);
- };
- const major = parsePart(parts[0]);
- const minor = parsePart(parts[1]);
- const patch = parsePart(parts[2]);
- return [
- major,
- minor,
- patch
- ];
-}
-function compareSemverTuples(a, b) {
- for (let i = 0;i < 3; i++) {
- if (a[i] < b[i])
- return -1;
- if (a[i] > b[i])
- return 1;
- }
- return 0;
-}
-function computeTildeBounds(value) {
- const parsed = parseSemver(value);
- const lower = [
- parsed[0],
- parsed[1],
- parsed[2]
- ];
- const upper = [
- parsed[0],
- parsed[1] + 1,
- 0
- ];
- return {
- lower,
- upper
- };
-}
-function computeCaretBounds(value) {
- const parsed = parseSemver(value);
- const [major, minor, patch] = parsed;
- const lower = [
- major,
- minor,
- patch
- ];
- let upper;
- upper = major > 0 ? [
- major + 1,
- 0,
- 0
- ] : minor > 0 ? [
- 0,
- minor + 1,
- 0
- ] : [
- 0,
- 0,
- patch + 1
- ];
- return {
- lower,
- upper
- };
-}
-function computeWildcardBounds(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
- if (!cleanedText)
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- const parts = cleanedText.split(".");
- const parseWildcardPart = (part) => {
- try {
- return parseSemverNumericIdentifier(part, value);
- } catch {
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- }
- };
- const major = parseWildcardPart(parts[0]);
- let lower;
- let upper;
- if (parts.length === 1) {
- lower = [
- major,
- 0,
- 0
- ];
- upper = [
- major + 1,
- 0,
- 0
- ];
- } else {
- const minor = parseWildcardPart(parts[1]);
- lower = [
- major,
- minor,
- 0
- ];
- upper = [
- major,
- minor + 1,
- 0
- ];
- }
- return {
- lower,
- upper
- };
-}
-function convertToDateTime(value) {
- if (value instanceof Date)
- return value;
- if (typeof value == "string" || typeof value == "number") {
- const date = new Date(value);
- if (!isNaN(date.valueOf()))
- return date;
- throw new InconclusiveMatchError(`${value} is in an invalid date format`);
- }
- throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
-}
-function relativeDateParseForFeatureFlagMatching(value) {
- const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
- const match = value.match(regex);
- const parsedDt = new Date(new Date().toISOString());
- if (!match)
- return null;
- {
- if (!match.groups)
- return null;
- const number = parseInt(match.groups["number"]);
- if (number >= 1e4)
- return null;
- const interval = match.groups["interval"];
- if (interval == "h")
- parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
- else if (interval == "d")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
- else if (interval == "w")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
- else if (interval == "m")
- parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
- else {
- if (interval != "y")
- return null;
- parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
- }
- return parsedDt;
- }
-}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
var UNHANDLED_REJECTION_OPTION_NAMES = [
"--unhandled-rejections",
"--unhandled_rejections"
@@ -5353,7 +7420,7 @@ function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJEC
});
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
var SHUTDOWN_TIMEOUT = 2000;
class error_tracking_ErrorTracking {
@@ -5423,8 +7490,9 @@ class error_tracking_ErrorTracking {
this._rateLimiter.stop();
}
}
+var error_tracking_default = error_tracking_ErrorTracking;
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
class PostHogMemoryStorage {
getProperty(key) {
return this._memoryStorage[key];
@@ -5437,16 +7505,16 @@ class PostHogMemoryStorage {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
function isCaptureMode(value) {
return value === "v0" || value === "v1";
}
function resolveCaptureMode() {
- const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
+ const envMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
return isCaptureMode(envMode) ? envMode : "v0";
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
var AI_EVENT_PREFIX = "$ai_";
var ANALYTICS_ROUTE = "analytics";
var AI_ROUTE = "ai";
@@ -5454,7 +7522,7 @@ function isLegacyOnlyEvent(message) {
return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
class CaptureV1Error extends Error {
constructor({ requestId, drops, retryExhausted, cause }) {
super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = "CaptureV1Error";
@@ -5471,7 +7539,7 @@ class CaptureV1Error extends Error {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
function coerceBool(value) {
if (typeof value == "boolean")
return value;
@@ -5586,7 +7654,7 @@ function buildV1Batch(messages, { createdAt, historicalMigration }) {
return batch;
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
var V1_ANALYTICS_PATH = "/i/v1/analytics/events";
var DEFAULT_MAX_BACKOFF_MS = 30000;
var RETRYABLE_STATUSES = new Set([
@@ -5839,13 +7907,13 @@ class V1CaptureSender {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
var AI_CAPTURE_ROUTE = "ai-capture";
var AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/";
var AI_MAX_EVENT_BYTES = 8388608;
var AI_BATCH_TARGET_BYTES = 5242880;
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
var encoder = new TextEncoder;
function eventByteSize(message) {
return encoder.encode(safeJsonStringify(message)).length;
@@ -5882,7 +7950,7 @@ function partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBa
};
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
var MINIMUM_POLLING_INTERVAL = 100;
var THIRTY_SECONDS = 30000;
var MAX_CACHE_SIZE = 50000;
@@ -5968,10 +8036,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
},
customHeaders: this.getCustomHeaders(),
cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
- strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
+ strictLocalEvaluation: normalizedOptions.strictLocalEvaluation,
+ evaluationContexts: normalizedOptions.evaluationContexts ?? normalizedOptions.evaluationEnvironments
});
}
- this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
+ this.errorTracking = new error_tracking_default(this, normalizedOptions, this._logger);
this.distinctIdHasSentFlagCalls = {};
this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
}
@@ -5979,8 +8048,26 @@ class PostHogBackendClient extends PostHogCoreStateless {
super.enqueue(type, message, options, explicitRoute);
this.scheduleDebouncedFlush();
}
+ _flushEventsAndSpans(skipThrottledSpans = false) {
+ const events = this.flushWithPendingPromises();
+ if (!this._traces || skipThrottledSpans && this._traces.throttled)
+ return events;
+ return allSettled([
+ events,
+ this._traces.flush().catch(() => {})
+ ]).then(([eventsResult]) => {
+ if (eventsResult.status === "rejected")
+ throw eventsResult.reason;
+ });
+ }
+ flushAutomatic() {
+ return this._flushKeepingRuntimeAlive(true);
+ }
async flush() {
- const flushPromise = this.flushWithPendingPromises();
+ return this._flushKeepingRuntimeAlive(false);
+ }
+ _flushKeepingRuntimeAlive(skipThrottledSpans) {
+ const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
const waitUntil = this.options.waitUntil;
if (waitUntil && !this._waitUntilCycle)
try {
@@ -6033,7 +8120,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
async resolveWaitUntilFlush() {
const resolve = this._consumeWaitUntilCycle();
try {
- await this.flushWithPendingPromises();
+ await this._flushEventsAndSpans();
} catch {} finally {
resolve?.();
}
@@ -6135,9 +8222,51 @@ class PostHogBackendClient extends PostHogCoreStateless {
this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
return this._metrics;
}
+ initializeSpanContextManager() {
+ return new SyncSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return {};
+ }
+ get _spanContextManager() {
+ if (!this._spanContext)
+ this._spanContext = this.initializeSpanContextManager();
+ return this._spanContext;
+ }
+ get _tracesPipeline() {
+ if (!this.options.traces)
+ return;
+ if (!this._traces)
+ this._traces = new PostHogTraces(this, resolveTracesConfig(this.options.traces, this.hostResourceAttributes(), this._logger), this._logger, () => this._tracingContext(), this._spanContextManager, () => this.scheduleDebouncedFlush());
+ return this._traces;
+ }
+ _tracingContext() {
+ const context = this.context?.get();
+ return {
+ distinctId: context?.distinctId,
+ sessionId: context?.sessionId
+ };
+ }
+ startSpan(name, options) {
+ return this._tracesPipeline?.startSpan(name, options) ?? inertSpan(options, this._spanContextManager.active());
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const pipeline = this._tracesPipeline;
+ if (!pipeline)
+ return runWithActiveSpan(this._spanContextManager, inertSpan(options, this._spanContextManager.active()), fn);
+ return options ? pipeline.withSpan(name, options, fn) : pipeline.withSpan(name, fn);
+ }
+ getActiveSpan() {
+ return this._spanContextManager.active() ?? null;
+ }
getCustomUserAgent() {
return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
}
+ getEvaluationRuntime() {
+ return "server";
+ }
getCommonEventProperties() {
const commonProperties = super.getCommonEventProperties();
if (this.options.isServer ?? true)
@@ -6625,7 +8754,16 @@ class PostHogBackendClient extends PostHogCoreStateless {
flags: {}
});
}
- const { groups, disableGeoip, flagKeys } = resolvedOptions || {};
+ const { groups, disableGeoip } = resolvedOptions || {};
+ const flagKeys = resolvedOptions?.flagKeys ?? undefined;
+ if (flagKeys?.length === 0)
+ return new FeatureFlagEvaluations({
+ host: this._getFeatureFlagEvaluationsHost(),
+ distinctId: resolvedDistinctId,
+ groups,
+ disableGeoip,
+ flags: {}
+ });
let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};
const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
personProperties = adjustedProperties.allPersonProperties;
@@ -6879,6 +9017,10 @@ class PostHogBackendClient extends PostHogCoreStateless {
await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
this._metrics.reset();
}
+ if (this._traces) {
+ await raceWithTimeout(this._traces.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
+ this._traces.reset();
+ }
try {
return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
} finally {
@@ -7007,9 +9149,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
};
}
captureException(error, distinctId, additionalProperties, uuid, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
...msg,
@@ -7019,9 +9161,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
}
}
async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ return this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this.captureImmediate({
...msg,
@@ -7131,7 +9273,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
import { AsyncLocalStorage } from "node:async_hooks";
class PostHogContext {
@@ -7162,7 +9304,22 @@ class PostHogContext {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/span-context.node.mjs
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
+
+class AsyncLocalStorageSpanContextManager {
+ active() {
+ return this._storage.getStore();
+ }
+ with(span, fn) {
+ return this._storage.run(span, fn);
+ }
+ constructor() {
+ this._storage = new AsyncLocalStorage2;
+ }
+}
+
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
import { gzip } from "node:zlib";
import { promisify } from "node:util";
var gzipAsync = promisify(gzip);
@@ -7177,7 +9334,19 @@ async function gzipCompress2(input, isDebug = true) {
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/host-os.node.mjs
+import { platform, release as release2 } from "node:os";
+function hostOsResourceAttributes() {
+ let osName;
+ let osVersion;
+ try {
+ osName = platform();
+ osVersion = release2();
+ } catch {}
+ return osResourceAttributes(osName, osVersion);
+}
+
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
var NAME = "posthog-node";
function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
"error"
@@ -7232,7 +9401,9 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
};
}
class PostHogSentryIntegration {
- static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ static {
+ this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ }
constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
this.name = NAME;
this.name = NAME;
@@ -7248,7 +9419,7 @@ class PostHogSentryIntegration {
};
}
}
-// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
+// ../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
class PostHog extends PostHogBackendClient {
getLibraryId() {
return "posthog-node";
@@ -7259,6 +9430,12 @@ class PostHog extends PostHogBackendClient {
initializeContext() {
return new PostHogContext;
}
+ initializeSpanContextManager() {
+ return new AsyncLocalStorageSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return hostOsResourceAttributes();
+ }
createErrorPropertiesBuilder() {
return new ErrorPropertiesBuilder([
new EventCoercer,
diff --git a/plugins/omo/components/telemetry/dist/posthog.js b/plugins/omo/components/telemetry/dist/posthog.js
index 903bc031..811961e0 100644
--- a/plugins/omo/components/telemetry/dist/posthog.js
+++ b/plugins/omo/components/telemetry/dist/posthog.js
@@ -380,7 +380,7 @@ function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST)
return env["POSTHOG_HOST"]?.trim() || defaultHost;
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
import { dirname as dirname2, posix, sep } from "path";
function createModulerModifier() {
const getModuleFromFileName = createGetModuleFromFilename();
@@ -416,139 +416,7 @@ function normalizeWindowsPath(path) {
return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
-var normalizeFlagsResponse = (flagsResponse) => {
- if ("flags" in flagsResponse) {
- const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
- const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads
- };
- }
- {
- const featureFlags = flagsResponse.featureFlags ?? {};
- const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
- k,
- parsePayload(v)
- ]));
- const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
- key,
- getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
- ]));
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads,
- flags
- };
- }
-};
-function getFlagDetailFromFlagAndPayload(key, value, payload) {
- return {
- key,
- enabled: typeof value == "string" ? true : value,
- variant: typeof value == "string" ? value : undefined,
- reason: undefined,
- metadata: {
- id: undefined,
- version: undefined,
- payload: payload ? JSON.stringify(payload) : undefined,
- description: undefined
- }
- };
-}
-var getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
- key,
- getFeatureFlagValue(detail)
-]).filter(([, value]) => value !== undefined));
-var getPayloadsFromFlags = (flags) => {
- const safeFlags = flags ?? {};
- return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
- const details = safeFlags[flag];
- return details.enabled && details.metadata && details.metadata.payload !== undefined;
- }).map((flag) => {
- const payload = safeFlags[flag].metadata?.payload;
- return [
- flag,
- payload ? parsePayload(payload) : undefined
- ];
- }));
-};
-var getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled;
-var parsePayload = (response) => {
- if (typeof response != "string")
- return response;
- try {
- return JSON.parse(response);
- } catch {
- return response;
- }
-};
-var MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
- "utm_source",
- "utm_medium",
- "utm_campaign",
- "utm_content",
- "utm_term",
- "gad_source",
- "mc_cid",
- "gclid",
- "gclsrc",
- "dclid",
- "gbraid",
- "wbraid",
- "fbclid",
- "msclkid",
- "twclid",
- "li_fat_id",
- "igshid",
- "ttclid",
- "rdt_cid",
- "epik",
- "qclid",
- "sccid",
- "irclid",
- "_kx"
-];
-var MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
- "$feature_flag",
- "$feature_flag_response",
- "$feature_flag_has_experiment",
- "$feature_flag_id",
- "$feature_flag_version",
- "$feature_flag_reason",
- "$feature_flag_request_id",
- "$feature_flag_evaluated_at",
- "$feature_flag_error",
- "locally_evaluated",
- "$groups",
- "$process_person_profile",
- "$geoip_disable",
- "$current_url",
- "$pathname",
- "$referring_domain",
- ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
- "$session_id",
- "$window_id",
- "$lib",
- "$lib_version",
- "$device_id",
- "$is_server"
-];
-var minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
- const minimal = {};
- const copyKey = (key) => {
- if (properties[key] !== undefined)
- minimal[key] = properties[key];
- };
- MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
- transportKeys.forEach(copyKey);
- return minimal;
-};
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
PostHogPersistedProperty["DistinctId"] = "distinct_id";
@@ -578,6 +446,7 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
PostHogPersistedProperty["PushRegistered"] = "push_registered";
PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
+ PostHogPersistedProperty["SurveysInProgress"] = "surveys_in_progress";
PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
PostHogPersistedProperty["Surveys"] = "surveys";
PostHogPersistedProperty["RemoteConfig"] = "remote_config";
@@ -586,108 +455,80 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
return PostHogPersistedProperty;
}({});
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
-function isGzipSupported() {
- return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
+function safeJsonStringify(value) {
+ const ancestors = [];
+ return JSON.stringify(value, function(_key, replacementValue) {
+ if (typeof replacementValue == "bigint")
+ return replacementValue.toString();
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
+ return;
+ if (replacementValue instanceof Error)
+ return {
+ name: replacementValue.name,
+ message: replacementValue.message,
+ stack: replacementValue.stack
+ };
+ if (replacementValue && typeof replacementValue == "object") {
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
+ ancestors.pop();
+ if (ancestors.includes(replacementValue))
+ return "[Circular]";
+ ancestors.push(replacementValue);
+ }
+ return replacementValue;
+ }) ?? "null";
}
-var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError";
-var GZIP_MAGIC_FIRST_BYTE = 31;
-var GZIP_MAGIC_SECOND_BYTE = 139;
-var GZIP_DEFLATE_METHOD = 8;
-var hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;
-var crc32Table;
-var getCrc32Table = () => {
- if (crc32Table)
- return crc32Table;
- crc32Table = [];
- for (let i = 0;i < 256; i++) {
- let crc = i;
- for (let j = 0;j < 8; j++)
- crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
- crc32Table[i] = crc >>> 0;
- }
- return crc32Table;
-};
-var crc32 = (bytes) => {
- const table = getCrc32Table();
- let crc = 4294967295;
- for (let i = 0;i < bytes.length; i++)
- crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
- return (4294967295 ^ crc) >>> 0;
-};
-var throwNativeGzipValidationError = (reason) => {
- const error = new Error(`Native gzip produced invalid output: ${reason}`);
- error.name = NATIVE_GZIP_VALIDATION_ERROR;
- throw error;
-};
-var validateNativeGzip = async (compressed, inputBytes) => {
- if (compressed.size < 18)
- throwNativeGzipValidationError("too-short");
- const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
- if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
- throwNativeGzipValidationError("invalid-header");
- const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
- if (trailer.getUint32(0, true) !== crc32(inputBytes))
- throwNativeGzipValidationError("invalid-crc");
- const inputSize = inputBytes.length >>> 0;
- if (trailer.getUint32(4, true) !== inputSize)
- throwNativeGzipValidationError("invalid-size");
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
+var nativeIsArray = Array.isArray;
+var ObjProto = Object.prototype;
+var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
+var type_utils_toString = ObjProto.toString;
+var isArray = nativeIsArray || function(obj) {
+ return type_utils_toString.call(obj) === "[object Array]";
};
-async function gzipCompress(input, isDebug = true, options) {
- try {
- const inputBytes = new TextEncoder().encode(input);
- const compressedStream = new globalThis.CompressionStream("gzip");
- const writer = compressedStream.writable.getWriter();
- const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
- try {
- await writer.abort(err);
- } catch {}
- throw err;
- });
- const responsePromise = new Response(compressedStream.readable).blob();
- const [compressed] = await Promise.all([
- responsePromise,
- writePromise
- ]);
- await validateNativeGzip(compressed, inputBytes);
- return compressed;
- } catch (error) {
- if (options?.rethrow)
- throw error;
- if (isDebug)
- console.error("Failed to gzip compress data", error);
- return null;
+var isObject = (x) => x === Object(x) && !isArray(x);
+var isUndefined = (x) => x === undefined;
+var isString = (x) => type_utils_toString.call(x) == "[object String]";
+var isEmptyString = (x) => isString(x) && x.trim().length === 0;
+var isNull = (x) => x === null;
+var isNullish = (x) => isUndefined(x) || isNull(x);
+var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
+var isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
+function isPrimitive(value) {
+ return value === null || typeof value != "object";
+}
+function isBuiltin(candidate, className) {
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
+}
+function isError(candidate) {
+ switch (Object.prototype.toString.call(candidate)) {
+ case "[object Error]":
+ case "[object Exception]":
+ case "[object DOMException]":
+ case "[object DOMError]":
+ case "[object WebAssembly.Exception]":
+ return true;
+ default:
+ return isInstanceOf(candidate, Error);
}
}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
-var MAX_JSON_SAFE_VALUE_DEPTH = 20;
-var MAX_JSON_SAFE_VALUE_ITEMS = 1000;
-var MAX_JSON_SAFE_VALUE_NODES = 1e4;
-var CIRCULAR_VALUE = "[Circular]";
-var TRUNCATED_VALUE = "[Truncated]";
-var UNSERIALIZABLE_VALUE = "[Unserializable]";
-var FUNCTION_VALUE = "[Function]";
-var dateGetTime = Date.prototype.getTime;
-var dateToISOString = Date.prototype.toISOString;
-function sanitizeString(value) {
- let output = "";
- for (let index = 0;index < value.length; index++) {
- const codeUnit = value.charCodeAt(index);
- if (codeUnit >= 55296 && codeUnit <= 56319) {
- const nextCodeUnit = value.charCodeAt(index + 1);
- if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
- output += value[index] + value[index + 1];
- index++;
- } else
- output += "�";
- } else
- output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
+function isEvent(candidate) {
+ return "u" > typeof Event && isInstanceOf(candidate, Event);
+}
+function isPlainObject(candidate) {
+ return isBuiltin(candidate, "Object");
+}
+function isInstanceOf(candidate, base) {
+ try {
+ return candidate instanceof base;
+ } catch {
+ return false;
}
- return output;
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
var DEFAULT_BLOCKED_UA_STRS = [
"amazonbot",
"amazonproductbot",
@@ -715,7 +556,7 @@ var DEFAULT_BLOCKED_UA_STRS = [
"msnbot",
"nessus",
"petalbot",
- "pinterest",
+ "pinterestbot",
"prerender",
"rogerbot",
"screaming frog",
@@ -776,79 +617,7 @@ var isBlockedUA = function(ua, customBlockedUserAgents = []) {
return uaLower.indexOf(blockedUaLower) !== -1;
});
};
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
-function safeJsonStringify(value) {
- const ancestors = [];
- return JSON.stringify(value, function(_key, replacementValue) {
- if (typeof replacementValue == "bigint")
- return replacementValue.toString();
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
- return;
- if (replacementValue instanceof Error)
- return {
- name: replacementValue.name,
- message: replacementValue.message,
- stack: replacementValue.stack
- };
- if (replacementValue && typeof replacementValue == "object") {
- while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
- ancestors.pop();
- if (ancestors.includes(replacementValue))
- return "[Circular]";
- ancestors.push(replacementValue);
- }
- return replacementValue;
- }) ?? "null";
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
-var nativeIsArray = Array.isArray;
-var ObjProto = Object.prototype;
-var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
-var type_utils_toString = ObjProto.toString;
-var isArray = nativeIsArray || function(obj) {
- return type_utils_toString.call(obj) === "[object Array]";
-};
-var isObject = (x) => x === Object(x) && !isArray(x);
-var isUndefined = (x) => x === undefined;
-var isString = (x) => type_utils_toString.call(x) == "[object String]";
-var isEmptyString = (x) => isString(x) && x.trim().length === 0;
-var isNull = (x) => x === null;
-var isNullish = (x) => isUndefined(x) || isNull(x);
-var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
-var isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
-function isPrimitive(value) {
- return value === null || typeof value != "object";
-}
-function isBuiltin(candidate, className) {
- return Object.prototype.toString.call(candidate) === `[object ${className}]`;
-}
-function isError(candidate) {
- switch (Object.prototype.toString.call(candidate)) {
- case "[object Error]":
- case "[object Exception]":
- case "[object DOMException]":
- case "[object DOMError]":
- case "[object WebAssembly.Exception]":
- return true;
- default:
- return isInstanceOf(candidate, Error);
- }
-}
-function isEvent(candidate) {
- return typeof Event != "undefined" && isInstanceOf(candidate, Event);
-}
-function isPlainObject(candidate) {
- return isBuiltin(candidate, "Object");
-}
-function isInstanceOf(candidate, base) {
- try {
- return candidate instanceof base;
- } catch {
- return false;
- }
-}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
function clampToRange(value, min, max, logger, fallbackValue) {
if (min > max) {
logger.warn("min cannot be greater than max.");
@@ -865,10 +634,10 @@ function clampToRange(value, min, max, logger, fallbackValue) {
return min;
}
logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
- return clampToRange(fallbackValue || max, min, max, logger);
+ return clampToRange(fallbackValue ?? max, min, max, logger);
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
var ONE_DAY_IN_MS = 86400000;
var DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;
var DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;
@@ -920,8 +689,8 @@ class BucketedRateLimiter {
this._buckets = {};
}
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
-/*! For license information please see uuidv7.mjs.LICENSE.txt */
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
+/*! LICENSE: uuidv7.mjs.LICENSE.txt */
var DIGITS = "0123456789abcdef";
class UUID {
@@ -1092,13 +861,13 @@ class V7Generator {
}
}
var getDefaultRandom = () => ({
- nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random()) >>> 0
});
var defaultGenerator;
var uuidv7 = () => uuidv7obj().toString();
var uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
class PromiseQueue {
add(promise) {
const promiseUUID = uuidv7();
@@ -1136,7 +905,7 @@ class PromiseQueue {
this.nextId = 0;
}
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
function createConsole(consoleLike = console) {
const lockedMethods = {
log: consoleLike.log.bind(consoleLike),
@@ -1177,7 +946,7 @@ var passThrough = (fn) => fn();
function createLogger(prefix, maybeCall = passThrough) {
return _createLogger(prefix, maybeCall, createConsole());
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
var MOBILE = "Mobile";
var IOS = "iOS";
var ANDROID = "Android";
@@ -1220,9 +989,13 @@ var DUCKDUCKGO = "DuckDuckGo";
var PALE_MOON = "Pale Moon";
var WATERFOX = "Waterfox";
var BRAVE = "Brave";
+var CLAUDE = "Claude";
+var CODEX = "Codex";
+var CHATGPT = "ChatGPT";
var GOOGLE_SEARCH_APP = "Google Search App";
var BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)";
var DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
+var AI_APP_VERSION_REGEX = new RegExp("(" + CLAUDE + "|" + CODEX + "|" + CHATGPT + ")\\/" + BROWSER_VERSION_REGEX_SUFFIX);
var XBOX_REGEX = new RegExp(XBOX, "i");
var PLAYSTATION_REGEX = new RegExp(PLAYSTATION + " \\w+", "i");
var NINTENDO_REGEX = new RegExp(NINTENDO + " \\w+", "i");
@@ -1299,6 +1072,15 @@ var versionRegexes = {
[BRAVE]: [
new RegExp(BRAVE + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
+ [CLAUDE]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CODEX]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CHATGPT]: [
+ AI_APP_VERSION_REGEX
+ ],
[DUCKDUCKGO]: [
new RegExp("(DuckDuckGo|Ddg)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
@@ -1469,8 +1251,121 @@ var osMatchers = [
]
]
];
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
+var MAX_JSON_SAFE_VALUE_DEPTH = 20;
+var MAX_JSON_SAFE_VALUE_ITEMS = 1000;
+var MAX_JSON_SAFE_VALUE_NODES = 1e4;
+var CIRCULAR_VALUE = "[Circular]";
+var TRUNCATED_VALUE = "[Truncated]";
+var UNSERIALIZABLE_VALUE = "[Unserializable]";
+var FUNCTION_VALUE = "[Function]";
+var dateGetTime = Date.prototype.getTime;
+var dateToISOString = Date.prototype.toISOString;
+function sanitizeString(value) {
+ let output = "";
+ for (let index = 0;index < value.length; index++) {
+ const codeUnit = value.charCodeAt(index);
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
+ const nextCodeUnit = value.charCodeAt(index + 1);
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
+ output += value[index] + value[index + 1];
+ index++;
+ } else
+ output += "�";
+ } else
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
+ }
+ return output;
+}
+function assignUserAttributes(target, source) {
+ if (!source)
+ return target;
+ let keys = [];
+ try {
+ keys = Object.keys(source);
+ } catch {
+ keys = [];
+ }
+ for (const key of keys) {
+ let value;
+ try {
+ value = source[key];
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ return target;
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/retry-after.mjs
+var MAX_RETRY_AFTER_MS = 300000;
+var CLOCK_STEP_TOLERANCE_MS = 5000;
+function parseRetryAfterMs(value, now = Date.now()) {
+ if (typeof value != "string" || !value)
+ return;
+ const raw = value.trim();
+ const trimmed = /^\d+\s*,/.test(raw) ? raw.slice(0, raw.indexOf(",")).trim() : raw;
+ if (/^\d+$/.test(trimmed)) {
+ const ms = 1000 * Math.min(Number(trimmed), MAX_RETRY_AFTER_MS / 1000);
+ return ms > 0 ? ms : undefined;
+ }
+ if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(trimmed))
+ return;
+ const date = /^\w{3} \w{3} /.test(trimmed) ? trimmed + " GMT" : trimmed;
+ const ms = Date.parse(date) - now;
+ if (!Number.isFinite(ms) || ms <= 0)
+ return;
+ return Math.min(ms, MAX_RETRY_AFTER_MS);
+}
+
+class RetryAfterWindow {
+ record(outcome) {
+ if (outcome.kind === "too-large")
+ return;
+ if (outcome.kind !== "retry-later")
+ return void this.reset();
+ if (!outcome.retryAfterMs)
+ return;
+ const open = this.isOpen();
+ const now = Date.now();
+ const asked = Math.min(outcome.retryAfterMs, MAX_RETRY_AFTER_MS);
+ if (!open) {
+ this._installedAt = now;
+ this._until = now + asked;
+ return;
+ }
+ this._until = Math.max(this._until, Math.min(now + asked, this._installedAt + MAX_RETRY_AFTER_MS));
+ }
+ remainingMs() {
+ const now = Date.now();
+ if (now < this._installedAt - CLOCK_STEP_TOLERANCE_MS) {
+ this.reset();
+ return 0;
+ }
+ const remaining = Math.min(MAX_RETRY_AFTER_MS, Math.max(0, this._until - now));
+ if (remaining === 0)
+ this.reset();
+ return remaining;
+ }
+ isOpen() {
+ return this.remainingMs() > 0;
+ }
+ reset() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+ constructor() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
var STRING_FORMAT = "utf8";
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isValidUUID(value) {
@@ -1479,6 +1374,18 @@ function isValidUUID(value) {
function getEventUuid(uuid, generateUuid) {
return isValidUUID(uuid) ? uuid : generateUuid();
}
+function createNamedError(name, message) {
+ const error = new Error(message);
+ try {
+ Object.defineProperty(error, "name", {
+ value: name,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ } catch {}
+ return error;
+}
function removeTrailingSlash(url) {
return url?.replace(/\/+$/, "");
}
@@ -1526,6 +1433,7 @@ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
clearTimeout(timeoutHandle);
}
}
+var isPromise = (obj) => obj && typeof obj.then == "function";
function allSettled(promises) {
return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
status: "fulfilled",
@@ -1536,2312 +1444,4803 @@ function allSettled(promises) {
}))));
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
-var OTLP_SEVERITY_MAP = {
- trace: {
- text: "TRACE",
- number: 1
- },
- debug: {
- text: "DEBUG",
- number: 5
- },
- info: {
- text: "INFO",
- number: 9
- },
- warn: {
- text: "WARN",
- number: 13
- },
- error: {
- text: "ERROR",
- number: 17
- },
- fatal: {
- text: "FATAL",
- number: 21
- }
-};
-var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
-var INT64_RANGE_LIMIT = 9223372036854776000;
-var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
-function newState() {
- return {
- ancestors: new WeakSet,
- remainingNodes: MAX_JSON_SAFE_VALUE_NODES
- };
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
+var parsedStackResults;
+var lastKeysCount;
+var cachedFilenameChunkIds;
+function getFilenameToChunkIdMap(stackParser) {
+ const chunkIdMap = globalThis._posthogChunkIds;
+ if (!chunkIdMap)
+ return;
+ const chunkIdKeys = Object.keys(chunkIdMap);
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
+ return cachedFilenameChunkIds;
+ lastKeysCount = chunkIdKeys.length;
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
+ if (!parsedStackResults)
+ parsedStackResults = {};
+ const result = parsedStackResults[stackKey];
+ if (result)
+ acc[result[0]] = result[1];
+ else {
+ const parsedStack = stackParser(stackKey);
+ for (let i = parsedStack.length - 1;i >= 0; i--) {
+ const stackFrame = parsedStack[i];
+ const filename = stackFrame?.filename;
+ const chunkId = chunkIdMap[stackKey];
+ if (filename && chunkId) {
+ acc[filename] = chunkId;
+ parsedStackResults[stackKey] = [
+ filename,
+ chunkId
+ ];
+ break;
+ }
+ }
+ }
+ return acc;
+ }, {});
+ return cachedFilenameChunkIds;
}
-function toOtlpKeyValueList(attrs, logger) {
- try {
- return encodeKeyValueList(attrs, logger, newState(), 0);
- } catch {
- return [];
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
+var MAX_EXCEPTIONS = 50;
+var MAX_AGGREGATE_MEMBER_INSPECTIONS = 1000;
+var MAX_ERROR_PROTOTYPE_DEPTH = 100;
+var MAX_WRAPPER_RECURSION = 4;
+
+class ErrorPropertiesBuilder {
+ constructor(coercers, stackParser, modifiers = []) {
+ this.coercers = coercers;
+ this.stackParser = stackParser;
+ this.modifiers = modifiers;
}
-}
-function encodeAnyValue(value, logger, state, depth) {
- if (state.remainingNodes <= 0)
- return {
- stringValue: TRUNCATED_VALUE
+ buildFromUnknown(input, hint = {}) {
+ const providedMechanism = hint && hint.mechanism;
+ const mechanism = providedMechanism || {
+ handled: true,
+ type: "generic"
};
- state.remainingNodes--;
- if (isBoolean(value))
- return {
- boolValue: value
- };
- if (typeof value == "number") {
- if (!Number.isFinite(value))
- return {
- stringValue: String(value)
- };
- if (Number.isInteger(value)) {
- if (Number.isSafeInteger(value))
- return {
- intValue: String(value)
- };
- if (typeof BigInt == "undefined")
- return {
- stringValue: String(value)
- };
- const decimal = BigInt(value).toString();
- if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
- logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
- return {
- stringValue: decimal
- };
- }
- return {
- intValue: decimal
- };
- }
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
+ const exceptionWithCause = coercingContext.apply(input);
+ const parsingContext = this.buildParsingContext(hint);
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
return {
- doubleValue: value
+ $exception_list: exceptionList,
+ $exception_level: "error"
};
}
- if (typeof value == "string")
- return {
- stringValue: sanitizeString(value)
- };
- if (typeof value == "function")
+ async modifyFrames(exceptionList) {
+ for (const exc of exceptionList)
+ if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
+ exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
+ return exceptionList;
+ }
+ coerceFallback(ctx) {
return {
- stringValue: FUNCTION_VALUE
+ type: "Error",
+ value: "Unknown error",
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
};
- if (typeof value == "symbol")
+ }
+ parseStacktrace(err, ctx) {
+ let cause;
+ if (err.cause != null)
+ cause = this.parseStacktrace(err.cause, ctx);
+ let stack;
+ if (err.stack != "" && err.stack != null)
+ try {
+ stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
+ } catch {}
return {
- stringValue: String(value)
+ ...err,
+ cause,
+ stack,
+ errors: err.errors?.map((child) => this.parseStacktrace(child, ctx))
};
- if (typeof value == "object" && value !== null) {
- if (state.ancestors.has(value))
- return {
- stringValue: CIRCULAR_VALUE
- };
- if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
- return {
- stringValue: TRUNCATED_VALUE
+ }
+ applyChunkIds(frames, chunkIdMap) {
+ return frames.map((frame) => {
+ if (frame.filename && chunkIdMap)
+ frame.chunk_id = chunkIdMap[frame.filename];
+ return frame;
+ });
+ }
+ applyCoercers(input, ctx) {
+ for (const adapter of this.coercers)
+ if (adapter.match(input))
+ return adapter.coerce(input, ctx);
+ return this.coerceFallback(ctx);
+ }
+ async applyModifiers(frames) {
+ let newFrames = frames;
+ for (const modifier of this.modifiers)
+ newFrames = await modifier(newFrames);
+ return newFrames;
+ }
+ convertToExceptionList(exceptionWithStack, mechanism) {
+ const exceptionList = [];
+ const append = (exception, parentId, source) => {
+ const exceptionId = exceptionList.length;
+ const entryMechanism = parentId === undefined ? {
+ type: typeof mechanism.type == "string" && mechanism.type.length > 0 ? mechanism.type : "generic",
+ ...typeof mechanism.handled == "boolean" ? {
+ handled: mechanism.handled
+ } : mechanism.handled === undefined ? {
+ handled: true
+ } : {},
+ synthetic: typeof mechanism.synthetic == "boolean" ? mechanism.synthetic : exception.synthetic,
+ exception_id: exceptionId
+ } : {
+ type: "chained",
+ source,
+ synthetic: exception.synthetic,
+ exception_id: exceptionId,
+ parent_id: parentId
};
- if (value instanceof Date) {
- const time = value.getTime();
- const iso = Number.isFinite(time) ? value.toISOString() : String(value);
- return {
- stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ const currentException = {
+ type: exception.type,
+ value: exception.value,
+ mechanism: entryMechanism
};
- }
- state.ancestors.add(value);
+ if (exception.stack)
+ currentException.stacktrace = {
+ type: "raw",
+ frames: exception.stack
+ };
+ exceptionList.push(currentException);
+ if (exception.cause)
+ append(exception.cause, exceptionId, "cause");
+ for (const child of exception.errors ?? [])
+ append(child, exceptionId, "member");
+ };
+ append(exceptionWithStack);
+ return exceptionList;
+ }
+ buildParsingContext(hint) {
+ const context = {
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
+ skipFirstLines: hint.skipFirstLines ?? 1
+ };
+ return context;
+ }
+ getAggregateErrors(input) {
try {
- try {
- const toJSON = value.toJSON;
- if (typeof toJSON == "function")
- return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
- } catch {}
- if (isArray(value))
- return {
- arrayValue: {
- values: encodeArrayValues(value, logger, state, depth + 1)
+ if (isError(input)) {
+ let prototype = Object.getPrototypeOf(input);
+ for (let depth = 0;prototype && depth < MAX_ERROR_PROTOTYPE_DEPTH; depth++) {
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
+ if (typeof constructor == "function" && constructor.name === "AggregateError") {
+ const errors = input.errors;
+ return isArray(errors) ? errors : undefined;
}
- };
- return {
- kvlistValue: {
- values: encodeKeyValueList(value, logger, state, depth + 1)
+ prototype = Object.getPrototypeOf(prototype);
}
- };
- } finally {
- state.ancestors.delete(value);
- }
+ }
+ } catch {}
}
- return {
- stringValue: sanitizeString(String(value))
- };
-}
-function encodeArrayValues(values, logger, state, depth) {
- const result = [];
- const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
- let index = 0;
- for (;index < itemCount && state.remainingNodes > 0; index++)
- try {
- const element = index in values ? values[index] : undefined;
- if (isNullish(element))
- continue;
- result.push(encodeAnyValue(element, logger, state, depth));
- } catch {
- result.push({
- stringValue: UNSERIALIZABLE_VALUE
- });
- }
- if (values.length > index)
- result.push({
- stringValue: TRUNCATED_VALUE
- });
- return result;
-}
-function encodeKeyValueList(attrs, logger, state, depth) {
- const result = [];
- for (const key in attrs)
- if (propertyIsEnumerable.call(attrs, key)) {
- if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
- logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
- break;
+ buildCoercingContext(mechanism, hint, depth = 0) {
+ let count = 0;
+ let memberInspections = 0;
+ let hasAggregate = false;
+ const seen = new Set;
+ const wrappers = [];
+ const skipped = {};
+ const coerce = (input, depth, wrapperDepth = 0) => {
+ const ctx = createContext(depth, wrapperDepth);
+ const forward = ctx.apply;
+ ctx.apply = (nextInput) => {
+ wrappers.push(input);
+ try {
+ return forward(nextInput);
+ } finally {
+ wrappers.pop();
+ }
+ };
+ if (wrapperDepth > MAX_WRAPPER_RECURSION || wrapperDepth > 0 && wrappers.indexOf(input) !== -1)
+ return this.coerceFallback(ctx);
+ const isReference = typeof input == "object" && input !== null || typeof input == "function";
+ if (wrapperDepth === 0 && count >= MAX_EXCEPTIONS || isReference && seen.has(input))
+ return;
+ if (isReference)
+ seen.add(input);
+ if (wrapperDepth === 0)
+ count++;
+ const errors = this.getAggregateErrors(input);
+ hasAggregate ||= !!errors;
+ let exception;
+ try {
+ exception = this.applyCoercers(input, ctx);
+ if (!exception)
+ throw skipped;
+ } catch (error) {
+ if (error === skipped) {
+ if (wrapperDepth === 0)
+ count--;
+ return;
+ }
+ if (!hasAggregate)
+ throw error;
+ exception = this.coerceFallback(ctx);
}
+ if (!errors || count >= MAX_EXCEPTIONS)
+ return exception;
+ let length;
try {
- const value = attrs[key];
- if (isNull(value) || isUndefined(value))
- continue;
- result.push({
- key: sanitizeString(key),
- value: encodeAnyValue(value, logger, state, depth)
- });
+ length = errors.length;
} catch {
- result.push({
- key: sanitizeString(key),
- value: {
- stringValue: UNSERIALIZABLE_VALUE
- }
- });
+ return exception;
}
- }
- return result;
-}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
-var DEFAULT_HISTOGRAM_BOUNDS = [
- 0,
- 5,
- 10,
- 25,
- 50,
- 75,
- 100,
- 250,
- 500,
- 750,
- 1000,
- 2500,
- 5000,
- 7500,
- 1e4
-];
-function msToUnixNano(ms) {
- return String(ms) + "000000";
-}
-function seriesKey(type, name, unit, attributes) {
- let attrsKey = "";
- if (attributes) {
- const keys = Object.keys(attributes).sort();
- attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
+ if (!Number.isInteger(length) || length < 0 || length > 4294967295)
+ return exception;
+ const children = [];
+ for (let index = 0;count < MAX_EXCEPTIONS && memberInspections < MAX_AGGREGATE_MEMBER_INSPECTIONS && index < length; index++) {
+ memberInspections++;
+ let child;
+ try {
+ child = ctx.next(errors[index]);
+ } catch {
+ count++;
+ child = this.coerceFallback(createContext(depth + 1));
+ }
+ if (child)
+ children.push(child);
+ }
+ return {
+ ...exception,
+ errors: children
+ };
+ };
+ const createContext = (depth, wrapperDepth = 0) => ({
+ ...hint,
+ syntheticException: depth == 0 ? hint.syntheticException : undefined,
+ mechanism: depth == 0 ? mechanism : {},
+ apply: (input) => {
+ const exception = coerce(input, depth, wrapperDepth + 1);
+ if (!exception)
+ throw skipped;
+ return exception;
+ },
+ next: (input) => coerce(input, depth + 1)
+ });
+ const context = createContext(depth);
+ return {
+ ...context,
+ apply: (input) => coerce(input, depth) ?? this.coerceFallback(context)
+ };
}
- return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
}
-function bucketIndexFor(value, bounds) {
- for (let i = 0;i < bounds.length; i++)
- if (value <= bounds[i])
- return i;
- return bounds.length;
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
+var UNKNOWN_FUNCTION = "?";
+var ANONYMOUS_FILENAME = "<anonymous>";
+var URL_SCHEME = /^([a-z][a-z0-9.+-]+):/i;
+var APP_URL_SCHEMES = [
+ "http",
+ "https",
+ "file",
+ "blob",
+ "app",
+ "capacitor",
+ "ionic",
+ "webpack",
+ "webpack-internal",
+ "ng"
+];
+function isAppFilename(filename) {
+ if (!filename || filename === ANONYMOUS_FILENAME)
+ return false;
+ const scheme = URL_SCHEME.exec(filename);
+ return !scheme || APP_URL_SCHEMES.includes(scheme[1].toLowerCase());
}
-function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
- return {
- ...config.resourceAttributes,
- "service.name": config.serviceName || "unknown_service",
- ...config.environment && {
- "deployment.environment": config.environment
- },
- ...config.serviceVersion && {
- "service.version": config.serviceVersion
- },
- "telemetry.sdk.name": scopeName,
- "telemetry.sdk.version": scopeVersion
- };
-}
-function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
- return {
- resourceMetrics: [
- {
- resource: {
- attributes: toOtlpKeyValueList(resourceAttributes)
- },
- scopeMetrics: [
- {
- scope: {
- name: scopeName,
- version: scopeVersion
- },
- metrics
- }
- ]
- }
- ]
- };
-}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
-var DEFAULT_FLUSH_INTERVAL_MS = 1e4;
-var DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
-function resolveMetricsConfig(config) {
- const resourceAttributes = config?.resourceAttributes;
- return {
- serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
- serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
- environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
- resourceAttributes,
- beforeSend: config?.beforeSend,
- flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
- maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
+function createFrame(platform, filename, func, lineno, colno) {
+ const frame = {
+ platform,
+ filename,
+ function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
+ in_app: isAppFilename(filename)
};
+ if (!isUndefined(lineno))
+ frame.lineno = lineno;
+ if (!isUndefined(colno))
+ frame.colno = colno;
+ return frame;
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
-var OTLP_TEMPORALITY_DELTA = 1;
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
+var extractSafariExtensionDetails = (func, filename) => {
+ const isSafariExtension = func.indexOf("safari-extension") !== -1;
+ const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
+ return isSafariExtension || isSafariWebExtension ? [
+ func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
+ ] : [
+ func,
+ filename
+ ];
+};
-class PostHogMetrics {
- constructor(_instance, _config, _logger) {
- this._instance = _instance;
- this._config = _config;
- this._logger = _logger;
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- this._generation = 0;
- }
- count(name, value = 1, options) {
- this._capture({
- name,
- type: "count",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- gauge(name, value, options) {
- this._capture({
- name,
- type: "gauge",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- histogram(name, value, options) {
- this._capture({
- name,
- type: "histogram",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- flush() {
- const prev = this._flushPromise;
- const run = async () => {
- if (prev)
- await prev.catch(() => {});
- await this._doFlush();
- };
- const p = run().finally(() => {
- if (this._flushPromise === p)
- this._flushPromise = null;
- });
- this._flushPromise = p;
- return p;
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
+var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
+var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
+var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
+var chromeStackLineParser = (line, platform) => {
+ const noFnParts = chromeRegexNoFnName.exec(line);
+ if (noFnParts) {
+ const [, filename, line, col] = noFnParts;
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
}
- drainWindow() {
- if (this._series.size === 0)
- return null;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- return this._buildPayload(window);
+ const parts = chromeRegex.exec(line);
+ if (parts) {
+ const isEval = parts[2] && parts[2].indexOf("eval") === 0;
+ if (isEval) {
+ const subMatch = chromeEvalRegex.exec(parts[2]);
+ if (subMatch) {
+ parts[2] = subMatch[1];
+ parts[3] = subMatch[2];
+ parts[4] = subMatch[3];
+ }
+ }
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
}
- reset() {
- this._generation++;
- this._clearFlushTimer();
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
+};
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
+var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
+var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
+var geckoStackLineParser = (line, platform) => {
+ const parts = geckoREgex.exec(line);
+ if (parts) {
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
+ if (isEval) {
+ const subMatch = geckoEvalRegex.exec(parts[3]);
+ if (subMatch) {
+ parts[1] = parts[1] || "eval";
+ parts[3] = subMatch[1];
+ parts[4] = subMatch[2];
+ parts[5] = "";
+ }
+ }
+ let filename = parts[3];
+ let func = parts[1] || UNKNOWN_FUNCTION;
+ [func, filename] = extractSafariExtensionDetails(func, filename);
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
}
- _capture(sample) {
- if (this._instance.isDisabled || this._instance.optedOut)
- return;
- const filtered = this._runBeforeSend(sample);
- if (filtered === null)
- return;
- if (!filtered.name || typeof filtered.name != "string")
- return void this._logger.warn("Dropping metric with empty name");
- if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
- return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
- if (filtered.type === "count" && filtered.value < 0)
- return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
- let attributes;
- let key;
- try {
- attributes = filtered.attributes ? {
- ...filtered.attributes
- } : undefined;
- key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
- } catch (e) {
- this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
- return;
+};
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
+var FILENAME_MATCH = /^\s*[-]{4,}$/;
+var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
+var PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
+var PROMISE_INDEX = /^index \d+$/;
+var PROMISE_FRAME_FILENAME = "node:internal/promise";
+var nodeStackLineParser = (line, platform) => {
+ const lineMatch = line.match(FULL_MATCH);
+ if (lineMatch) {
+ let object;
+ let method;
+ let functionName;
+ let typeName;
+ let methodName;
+ if (lineMatch[1]) {
+ functionName = lineMatch[1];
+ let methodStart = functionName.lastIndexOf(".");
+ if (functionName[methodStart - 1] === ".")
+ methodStart--;
+ if (methodStart > 0) {
+ object = functionName.slice(0, methodStart);
+ method = functionName.slice(methodStart + 1);
+ const objectEnd = object.indexOf(".Module");
+ if (objectEnd > 0) {
+ functionName = functionName.slice(objectEnd + 1);
+ object = object.slice(0, objectEnd);
+ }
+ }
+ typeName = undefined;
}
- let state = this._series.get(key);
- if (!state) {
- if (!this._admitNewSeries())
- return;
- state = {
- name: filtered.name,
- type: filtered.type,
- unit: filtered.unit,
- attributes,
- windowStartMs: Date.now()
- };
- this._series.set(key, state);
+ if (method) {
+ typeName = object;
+ methodName = method;
}
- const seenType = this._typeByName.get(filtered.name);
- if (seenType === undefined)
- this._typeByName.set(filtered.name, filtered.type);
- else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
- this._typeCollisionWarned.add(filtered.name);
- this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
+ if (method === "<anonymous>") {
+ methodName = undefined;
+ functionName = undefined;
}
- this._fold(state, filtered.value);
- this._armFlushTimer();
- }
- _admitNewSeries() {
- if (this._series.size < this._config.maxSeriesPerFlush)
- return true;
- if (!this._seriesCapWarned) {
- this._seriesCapWarned = true;
- this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
+ if (functionName === undefined) {
+ methodName = methodName || UNKNOWN_FUNCTION;
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
}
- return false;
- }
- _fold(state, value) {
- switch (state.type) {
- case "count":
- state.total = (state.total ?? 0) + value;
- break;
- case "gauge":
- state.last = value;
- break;
- case "histogram": {
- if (!state.hist)
- state.hist = {
- count: 0,
- sum: 0,
- min: value,
- max: value,
- bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
- };
- const hist = state.hist;
- hist.count += 1;
- hist.sum += value;
- hist.min = Math.min(hist.min, value);
- hist.max = Math.max(hist.max, value);
- hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
+ let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
+ const isNative = lineMatch[5] === "native";
+ if (filename?.match(/\/[A-Z]:/))
+ filename = filename.slice(1);
+ if (!filename && lineMatch[5] && !isNative)
+ filename = lineMatch[5];
+ if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
+ filename = PROMISE_FRAME_FILENAME;
+ return {
+ filename: filename ? decodeURI(filename) : undefined,
+ module: undefined,
+ function: functionName,
+ lineno: _parseIntOrUndefined(lineMatch[3]),
+ colno: _parseIntOrUndefined(lineMatch[4]),
+ in_app: filenameIsInApp(filename || "", isNative),
+ platform
+ };
+ }
+ if (line.match(FILENAME_MATCH))
+ return {
+ filename: line,
+ platform
+ };
+};
+function filenameIsInApp(filename, isNative = false) {
+ const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
+ return !isInternal && filename !== undefined && !filename.includes("node_modules/");
+}
+function _parseIntOrUndefined(input) {
+ return parseInt(input || "", 10) || undefined;
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
+var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
+var STACKTRACE_FRAME_LIMIT = 50;
+var MAX_REPEATED_CYCLE_LENGTH = 10;
+var STACKTRACE_LINE_LIMIT = 1000;
+function isSameFrame(a, b) {
+ return a.filename === b.filename && a.function === b.function && a.module === b.module && a.lineno === b.lineno && a.colno === b.colno;
+}
+function collapseRepeatedCycle(frames) {
+ for (let length = 1;length <= MAX_REPEATED_CYCLE_LENGTH; length++) {
+ const start = frames.length - 2 * length;
+ if (start < 0)
+ break;
+ let isCycle = true;
+ for (let offset = 0;offset < length; offset++) {
+ const inner = frames[start + offset];
+ if (!isSameFrame(inner, frames[start + length + offset])) {
+ isCycle = false;
break;
}
}
+ if (isCycle) {
+ for (let offset = 0;offset < length; offset++)
+ frames[start + offset] = frames[start + length + offset];
+ frames.length = start + length;
+ return {
+ start,
+ length
+ };
+ }
}
- _runBeforeSend(sample) {
- const beforeSend = this._config.beforeSend;
- if (!beforeSend)
- return sample;
- const fns = isArray(beforeSend) ? beforeSend : [
- beforeSend
- ];
- let result = sample;
- for (const fn of fns)
- try {
- const next = fn(result);
- if (!next) {
- this._logger.info("Metric was rejected in beforeSend function");
- return null;
+}
+function trimPartialCycle(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ const partialLength = partialCycleLength(frames, cycle);
+ if (partialLength)
+ frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength);
+}
+function innermostPartialCycleLength(frames, cycle) {
+ let partialStart = cycle.start;
+ while (partialStart > 0 && isSameFrame(frames[partialStart - 1], frames[partialStart - 1 + cycle.length]))
+ partialStart--;
+ return cycle.start - partialStart;
+}
+function partialCycleLength(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ let partialEnd = copyEnd;
+ while (partialEnd < frames.length && isSameFrame(frames[partialEnd], frames[partialEnd - cycle.length]))
+ partialEnd++;
+ return partialEnd - copyEnd;
+}
+function survivingFrameCount(frames, cycles) {
+ const innermostCycle = cycles[0];
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0);
+ for (const cycle of cycles)
+ count -= partialCycleLength(frames, cycle);
+ return count;
+}
+function canonicalizeCycleRotation(frames) {
+ const keys = frames.map((frame) => `${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`);
+ let first = 0;
+ for (let i = 1;i < keys.length; i++)
+ if (isSmallerRotation(keys, i, first))
+ first = i;
+ frames.push(...frames.splice(0, first));
+}
+function isSmallerRotation(keys, candidate, best) {
+ for (let offset = 0;offset < keys.length; offset++) {
+ const left = keys[(candidate + offset) % keys.length];
+ const right = keys[(best + offset) % keys.length];
+ if (left !== right)
+ return left < right;
+ }
+ return false;
+}
+function reverseAndStripFrames(stack) {
+ if (!stack.length)
+ return [];
+ const localStack = Array.from(stack);
+ localStack.reverse();
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
+ ...frame,
+ filename: frame.filename || getLastStackFrame(localStack).filename,
+ function: frame.function || UNKNOWN_FUNCTION
+ }));
+}
+function getLastStackFrame(arr) {
+ return arr[arr.length - 1] || {};
+}
+function createDefaultStackParser() {
+ return createStackParser("web:javascript", chromeStackLineParser, geckoStackLineParser);
+}
+function createStackParser(platform, ...parsers) {
+ return (stack, skipFirstLines = 0) => {
+ const frames = [];
+ const lines = stack.split(`
+`);
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT);
+ const repeatedCycles = [];
+ for (let i = skipFirstLines;i < endLine; i++) {
+ const line = lines[i];
+ if (line.length > 1024)
+ continue;
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
+ if (!cleanedLine.match(/\S*Error: /)) {
+ for (const parser of parsers) {
+ const frame = parser(cleanedLine, platform);
+ if (frame) {
+ frames.push(frame);
+ const cycle = collapseRepeatedCycle(frames);
+ if (cycle) {
+ for (let i = repeatedCycles.length - 1;i >= 0; i--) {
+ const previous = repeatedCycles[i];
+ if (previous.start + previous.length <= cycle.start)
+ break;
+ repeatedCycles.pop();
+ }
+ repeatedCycles.push(cycle);
+ }
+ break;
+ }
}
- result = next;
- } catch (e) {
- this._logger.error("Error in beforeSend function for metric:", e);
- return null;
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT)
+ break;
}
- return result;
+ }
+ const sections = [
+ ...repeatedCycles
+ ].sort((a, b) => b.start - a.start);
+ const innermostSection = sections[sections.length - 1];
+ if (innermostSection) {
+ const trimmed = innermostPartialCycleLength(frames, innermostSection);
+ frames.splice(innermostSection.start - trimmed, trimmed);
+ for (const cycle of sections)
+ cycle.start -= trimmed;
+ }
+ for (const cycle of sections)
+ trimPartialCycle(frames, cycle);
+ if (repeatedCycles.some((cycle) => cycle.start === 0 && frames.length === cycle.length))
+ canonicalizeCycleRotation(frames);
+ return reverseAndStripFrames(frames);
+ };
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
+class ErrorCoercer {
+ match(err) {
+ return isError(err);
}
- _armFlushTimer() {
- if (this._flushTimer)
- return;
- this._flushTimer = safeSetTimeout(() => {
- this._flushTimer = undefined;
- this.flush().catch((e) => {
- this._logger.error("Metrics flush failed:", e);
- });
- }, this._config.flushIntervalMs);
+ coerce(err, ctx) {
+ const stack = this.getStack(err);
+ const replacementStack = stack === undefined ? ctx.syntheticException?.stack : undefined;
+ const synthetic = !!replacementStack;
+ return {
+ type: this.getType(err),
+ value: this.getMessage(err, ctx),
+ stack: stack ?? replacementStack,
+ cause: err.cause ? ctx.next(err.cause) : undefined,
+ synthetic
+ };
}
- _clearFlushTimer() {
- if (this._flushTimer) {
- clearTimeout(this._flushTimer);
- this._flushTimer = undefined;
- }
+ getType(err) {
+ return err.name || err.constructor.name;
}
- async _doFlush() {
- if (this._series.size === 0)
- return;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- const generation = this._generation;
- const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
- if (generation !== this._generation)
+ getMessage(err, _ctx) {
+ const message = err.message;
+ if (message.error && typeof message.error.message == "string")
+ return String(message.error.message);
+ return String(message);
+ }
+ getStack(err) {
+ try {
+ const stacktrace = err.stacktrace;
+ if (typeof stacktrace == "string" && stacktrace.length > 0)
+ return stacktrace;
+ const stack = err.stack;
+ return typeof stack == "string" && stack.length > 0 ? stack : undefined;
+ } catch {
return;
- switch (outcome.kind) {
- case "ok":
- return;
- case "retry-later":
- this._mergeWindowBack(window);
- this._armFlushTimer();
- return;
- case "too-large":
- this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
- return;
- case "fatal":
- this._logger.error("Failed to send metrics batch:", outcome.error);
- return;
}
}
- _buildPayload(window) {
- return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
+var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
+
+class StringCoercer {
+ match(input) {
+ return typeof input == "string";
}
- _buildMetrics(window) {
- const nowNano = msToUnixNano(Date.now());
- const byMetric = new Map;
- for (const state of window.values()) {
- const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
- let metric = byMetric.get(metricKey);
- if (!metric) {
- metric = {
- name: state.name,
- ...state.unit && {
- unit: state.unit
- }
- };
- if (state.type === "count")
- metric.sum = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- isMonotonic: true,
- dataPoints: []
- };
- else if (state.type === "gauge")
- metric.gauge = {
- dataPoints: []
- };
- else
- metric.histogram = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- dataPoints: []
- };
- byMetric.set(metricKey, metric);
- }
- const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
- const startNano = msToUnixNano(state.windowStartMs);
- if (state.type === "count") {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- asDouble: state.total ?? 0
- };
- metric.sum.dataPoints.push(dp);
- } else if (state.type === "gauge") {
- const dp = {
- attributes,
- timeUnixNano: nowNano,
- asDouble: state.last ?? 0
- };
- metric.gauge.dataPoints.push(dp);
- } else if (state.hist) {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- count: state.hist.count,
- sum: state.hist.sum,
- min: state.hist.min,
- max: state.hist.max,
- bucketCounts: state.hist.bucketCounts,
- explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
- };
- metric.histogram.dataPoints.push(dp);
- }
+ coerce(input, ctx) {
+ const [type, value] = this.getInfos(input);
+ return {
+ type: type ?? "Error",
+ value: value ?? input,
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
+ };
+ }
+ getInfos(candidate) {
+ let type = "Error";
+ let value = candidate;
+ const groups = candidate.match(ERROR_TYPES_PATTERN);
+ if (groups) {
+ type = groups[1];
+ value = groups[2];
}
- return Array.from(byMetric.values());
+ return [
+ type,
+ value
+ ];
}
- _mergeWindowBack(window) {
- for (const [key, old] of window) {
- const current = this._series.get(key);
- if (!current) {
- if (this._admitNewSeries())
- this._series.set(key, old);
- continue;
- }
- current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
- switch (current.type) {
- case "count":
- current.total = (current.total ?? 0) + (old.total ?? 0);
- break;
- case "gauge":
- break;
- case "histogram":
- if (old.hist)
- if (current.hist) {
- current.hist.count += old.hist.count;
- current.hist.sum += old.hist.sum;
- current.hist.min = Math.min(current.hist.min, old.hist.min);
- current.hist.max = Math.max(current.hist.max, old.hist.max);
- for (let i = 0;i < current.hist.bucketCounts.length; i++)
- current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
- } else
- current.hist = old.hist;
- break;
- }
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
+var severityLevels = [
+ "fatal",
+ "error",
+ "warning",
+ "log",
+ "info",
+ "debug"
+];
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
+function extractExceptionKeysForMessage(err, maxLength = 40) {
+ const keys = Object.keys(err);
+ keys.sort();
+ if (!keys.length)
+ return "[object has no keys]";
+ for (let i = keys.length;i > 0; i--) {
+ const serialized = keys.slice(0, i).join(", ");
+ if (!(serialized.length > maxLength)) {
+ if (i === keys.length)
+ return serialized;
+ return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
}
}
+ return "";
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
-class SimpleEventEmitter {
- constructor() {
- this.events = {};
- this.events = {};
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
+class ObjectCoercer {
+ match(candidate) {
+ return typeof candidate == "object" && candidate !== null;
}
- on(event, listener) {
- if (!this.events[event])
- this.events[event] = [];
- this.events[event].push(listener);
- return () => {
- this.events[event] = this.events[event].filter((x) => x !== listener);
+ coerce(candidate, ctx) {
+ const errorProperty = this.getErrorPropertyFromObject(candidate);
+ if (errorProperty)
+ return ctx.apply(errorProperty);
+ return {
+ type: this.getType(candidate),
+ value: this.getValue(candidate),
+ stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
+ level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
+ synthetic: true
};
}
- emit(event, payload) {
- for (const listener of this.events[event] || [])
- listener(payload);
- for (const listener of this.events["*"] || [])
- listener(event, payload);
+ getType(err) {
+ if (isEvent(err))
+ return err.constructor.name;
+ const name = "name" in err ? err.name : undefined;
+ return isString(name) && !isEmptyString(name) ? name : "Error";
}
-}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
-var parsedStackResults;
-var lastKeysCount;
-var cachedFilenameChunkIds;
-function getFilenameToChunkIdMap(stackParser) {
- const chunkIdMap = globalThis._posthogChunkIds;
- if (!chunkIdMap)
- return;
- const chunkIdKeys = Object.keys(chunkIdMap);
- if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
- return cachedFilenameChunkIds;
- lastKeysCount = chunkIdKeys.length;
- cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
- if (!parsedStackResults)
- parsedStackResults = {};
- const result = parsedStackResults[stackKey];
- if (result)
- acc[result[0]] = result[1];
- else {
- const parsedStack = stackParser(stackKey);
- for (let i = parsedStack.length - 1;i >= 0; i--) {
- const stackFrame = parsedStack[i];
- const filename = stackFrame?.filename;
- const chunkId = chunkIdMap[stackKey];
- if (filename && chunkId) {
- acc[filename] = chunkId;
- parsedStackResults[stackKey] = [
- filename,
- chunkId
- ];
- break;
- }
+ getValue(err) {
+ if ("name" in err && typeof err.name == "string") {
+ let message = `'${err.name}' captured as exception`;
+ if ("message" in err && typeof err.message == "string")
+ message += ` with message: '${err.message}'`;
+ return message;
+ }
+ if ("message" in err && typeof err.message == "string")
+ return err.message;
+ const className = this.getObjectClassName(err);
+ const keys = extractExceptionKeysForMessage(err);
+ return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
+ }
+ isSeverityLevel(x) {
+ return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
+ }
+ getStack(candidate) {
+ try {
+ if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
+ return candidate.stacktrace;
+ return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
+ } catch {
+ return;
+ }
+ }
+ getErrorPropertyFromObject(obj) {
+ for (const prop in obj)
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
+ const value = obj[prop];
+ if (isError(value))
+ return value;
}
+ }
+ getObjectClassName(obj) {
+ try {
+ const prototype = Object.getPrototypeOf(obj);
+ return prototype ? prototype.constructor.name : undefined;
+ } catch (e) {
+ return;
}
- return acc;
- }, {});
- return cachedFilenameChunkIds;
+ }
}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
-var MAX_CAUSE_RECURSION = 4;
-
-class ErrorPropertiesBuilder {
- constructor(coercers, stackParser, modifiers = []) {
- this.coercers = coercers;
- this.stackParser = stackParser;
- this.modifiers = modifiers;
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
+class EventCoercer {
+ match(err) {
+ return isEvent(err);
}
- buildFromUnknown(input, hint = {}) {
- const providedMechanism = hint && hint.mechanism;
- const mechanism = providedMechanism || {
- handled: true,
- type: "generic"
- };
- const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
- const exceptionWithCause = coercingContext.apply(input);
- const parsingContext = this.buildParsingContext(hint);
- const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
- const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
+ coerce(evt, ctx) {
+ const constructorName = evt.constructor.name;
return {
- $exception_list: exceptionList,
- $exception_level: "error"
+ type: constructorName,
+ value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
};
}
- async modifyFrames(exceptionList) {
- for (const exc of exceptionList)
- if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
- exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
- return exceptionList;
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
+class PrimitiveCoercer {
+ match(candidate) {
+ return isPrimitive(candidate);
}
- coerceFallback(ctx) {
+ coerce(value, ctx) {
return {
type: "Error",
- value: "Unknown error",
+ value: `Primitive value captured as exception: ${String(value)}`,
stack: ctx.syntheticException?.stack,
synthetic: true
};
}
- parseStacktrace(err, ctx) {
- let cause;
- if (err.cause != null)
- cause = this.parseStacktrace(err.cause, ctx);
- let stack;
- if (err.stack != "" && err.stack != null)
- stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
- return {
- ...err,
- cause,
- stack
- };
- }
- applyChunkIds(frames, chunkIdMap) {
- return frames.map((frame) => {
- if (frame.filename && chunkIdMap)
- frame.chunk_id = chunkIdMap[frame.filename];
- return frame;
- });
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
+class ReduceableCache {
+ constructor(_maxSize) {
+ this._maxSize = _maxSize;
+ this._cache = new Map;
}
- applyCoercers(input, ctx) {
- for (const adapter of this.coercers)
- if (adapter.match(input))
- return adapter.coerce(input, ctx);
- return this.coerceFallback(ctx);
+ get(key) {
+ const value = this._cache.get(key);
+ if (value === undefined)
+ return;
+ this._cache.delete(key);
+ this._cache.set(key, value);
+ return value;
}
- async applyModifiers(frames) {
- let newFrames = frames;
- for (const modifier of this.modifiers)
- newFrames = await modifier(newFrames);
- return newFrames;
+ set(key, value) {
+ this._cache.set(key, value);
}
- convertToExceptionList(exceptionWithStack, mechanism) {
- const currentException = {
- type: exceptionWithStack.type,
- value: exceptionWithStack.value,
- mechanism: {
- type: mechanism.type ?? "generic",
- handled: mechanism.handled ?? true,
- synthetic: exceptionWithStack.synthetic ?? false
- }
- };
- if (exceptionWithStack.stack)
- currentException.stacktrace = {
- type: "raw",
- frames: exceptionWithStack.stack
- };
- const exceptionList = [
- currentException
- ];
- if (exceptionWithStack.cause != null)
- exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
- ...mechanism,
- handled: true
- }));
- return exceptionList;
+ reduce() {
+ while (this._cache.size >= this._maxSize) {
+ const value = this._cache.keys().next().value;
+ if (value)
+ this._cache.delete(value);
+ }
}
- buildParsingContext(hint) {
- const context = {
- chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
- skipFirstLines: hint.skipFirstLines ?? 1
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
+var EXCEPTION_STEP_INTERNAL_FIELDS = {
+ MESSAGE: "$message",
+ TIMESTAMP: "$timestamp"
+};
+var RESERVED_EXCEPTION_STEP_KEYS = new Set([
+ EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
+ EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
+]);
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
+function getInjectedReleaseId() {
+ const injected = globalThis._posthogReleaseId;
+ return typeof injected == "string" && injected.length > 0 ? injected : undefined;
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
+var normalizeFlagsResponse = (flagsResponse) => {
+ if ("flags" in flagsResponse) {
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads
};
- return context;
}
- buildCoercingContext(mechanism, hint, depth = 0) {
- const coerce = (input, depth) => {
- if (!(depth <= MAX_CAUSE_RECURSION))
- return;
- {
- const ctx = this.buildCoercingContext(mechanism, hint, depth);
- return this.applyCoercers(input, ctx);
- }
- };
- const context = {
- ...hint,
- syntheticException: depth == 0 ? hint.syntheticException : undefined,
- mechanism,
- apply: (input) => coerce(input, depth),
- next: (input) => coerce(input, depth + 1)
+ {
+ const featureFlags = flagsResponse.featureFlags ?? {};
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
+ k,
+ parsePayload(v)
+ ]));
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
+ key,
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
+ ]));
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads,
+ flags
};
- return context;
}
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
-var UNKNOWN_FUNCTION = "?";
-var MASKED_URL_PREFIX = "webkit-masked-url://";
-var ANONYMOUS_FILENAME = "<anonymous>";
-function createFrame(platform, filename, func, lineno, colno) {
- const frame = {
- platform,
- filename,
- function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
- in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
+};
+function getFlagDetailFromFlagAndPayload(key, value, payload) {
+ return {
+ key,
+ enabled: typeof value == "string" ? true : value,
+ variant: typeof value == "string" ? value : undefined,
+ reason: undefined,
+ metadata: {
+ id: undefined,
+ version: undefined,
+ payload: payload ? JSON.stringify(payload) : undefined,
+ description: undefined
+ }
};
- if (!isUndefined(lineno))
- frame.lineno = lineno;
- if (!isUndefined(colno))
- frame.colno = colno;
- return frame;
}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
-var extractSafariExtensionDetails = (func, filename) => {
- const isSafariExtension = func.indexOf("safari-extension") !== -1;
- const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
- return isSafariExtension || isSafariWebExtension ? [
- func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
- isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
- ] : [
- func,
- filename
- ];
+var getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
+ key,
+ getFeatureFlagValue(detail)
+]).filter(([, value]) => value !== undefined));
+var getPayloadsFromFlags = (flags) => {
+ const safeFlags = flags ?? {};
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
+ const details = safeFlags[flag];
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
+ }).map((flag) => {
+ const payload = safeFlags[flag].metadata?.payload;
+ return [
+ flag,
+ payload ? parsePayload(payload) : undefined
+ ];
+ }));
+};
+var getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled;
+var parsePayload = (response) => {
+ if (typeof response != "string")
+ return response;
+ try {
+ return JSON.parse(response);
+ } catch {
+ return response;
+ }
+};
+var MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_content",
+ "utm_term",
+ "gad_source",
+ "mc_cid",
+ "gclid",
+ "gclsrc",
+ "dclid",
+ "gbraid",
+ "wbraid",
+ "fbclid",
+ "msclkid",
+ "twclid",
+ "li_fat_id",
+ "igshid",
+ "ttclid",
+ "rdt_cid",
+ "epik",
+ "qclid",
+ "sccid",
+ "irclid",
+ "_kx"
+];
+var MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
+ "$feature_flag",
+ "$feature_flag_response",
+ "$feature_flag_has_experiment",
+ "$feature_flag_id",
+ "$feature_flag_version",
+ "$feature_flag_reason",
+ "$feature_flag_request_id",
+ "$feature_flag_evaluated_at",
+ "$feature_flag_error",
+ "locally_evaluated",
+ "$groups",
+ "$process_person_profile",
+ "$geoip_disable",
+ "$current_url",
+ "$pathname",
+ "$referring_domain",
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
+ "$session_id",
+ "$window_id",
+ "$lib",
+ "$lib_version",
+ "$device_id",
+ "$is_server"
+];
+var minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
+ const minimal = {};
+ const copyKey = (key) => {
+ if (properties[key] !== undefined)
+ minimal[key] = properties[key];
+ };
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
+ transportKeys.forEach(copyKey);
+ return minimal;
};
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
-var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
-var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
-var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
-var chromeStackLineParser = (line, platform) => {
- const noFnParts = chromeRegexNoFnName.exec(line);
- if (noFnParts) {
- const [, filename, line, col] = noFnParts;
- return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
+class SimpleEventEmitter {
+ constructor() {
+ this.events = {};
+ this.events = {};
}
- const parts = chromeRegex.exec(line);
- if (parts) {
- const isEval = parts[2] && parts[2].indexOf("eval") === 0;
- if (isEval) {
- const subMatch = chromeEvalRegex.exec(parts[2]);
- if (subMatch) {
- parts[2] = subMatch[1];
- parts[3] = subMatch[2];
- parts[4] = subMatch[3];
- }
- }
- const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
- return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
+ on(event, listener) {
+ if (!this.events[event])
+ this.events[event] = [];
+ this.events[event].push(listener);
+ return () => {
+ this.events[event] = this.events[event].filter((x) => x !== listener);
+ };
}
-};
+ emit(event, payload) {
+ for (const listener of this.events[event] || [])
+ listener(payload);
+ for (const listener of this.events["*"] || [])
+ listener(event, payload);
+ }
+}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
-var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
-var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
-var geckoStackLineParser = (line, platform) => {
- const parts = geckoREgex.exec(line);
- if (parts) {
- const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
- if (isEval) {
- const subMatch = geckoEvalRegex.exec(parts[3]);
- if (subMatch) {
- parts[1] = parts[1] || "eval";
- parts[3] = subMatch[1];
- parts[4] = subMatch[2];
- parts[5] = "";
- }
- }
- let filename = parts[3];
- let func = parts[1] || UNKNOWN_FUNCTION;
- [func, filename] = extractSafariExtensionDetails(func, filename);
- return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
+function isGzipSupported() {
+ return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+}
+var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError";
+var GZIP_MAGIC_FIRST_BYTE = 31;
+var GZIP_MAGIC_SECOND_BYTE = 139;
+var GZIP_DEFLATE_METHOD = 8;
+var hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;
+var crc32Table;
+var getCrc32Table = () => {
+ if (crc32Table)
+ return crc32Table;
+ crc32Table = [];
+ for (let i = 0;i < 256; i++) {
+ let crc = i;
+ for (let j = 0;j < 8; j++)
+ crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
+ crc32Table[i] = crc >>> 0;
}
+ return crc32Table;
};
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
-var FILENAME_MATCH = /^\s*[-]{4,}$/;
-var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
-var PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
-var PROMISE_INDEX = /^index \d+$/;
-var PROMISE_FRAME_FILENAME = "node:internal/promise";
-var nodeStackLineParser = (line, platform) => {
- const lineMatch = line.match(FULL_MATCH);
- if (lineMatch) {
- let object;
- let method;
- let functionName;
- let typeName;
- let methodName;
- if (lineMatch[1]) {
- functionName = lineMatch[1];
- let methodStart = functionName.lastIndexOf(".");
- if (functionName[methodStart - 1] === ".")
- methodStart--;
- if (methodStart > 0) {
- object = functionName.slice(0, methodStart);
- method = functionName.slice(methodStart + 1);
- const objectEnd = object.indexOf(".Module");
- if (objectEnd > 0) {
- functionName = functionName.slice(objectEnd + 1);
- object = object.slice(0, objectEnd);
+var crc32 = (bytes) => {
+ const table = getCrc32Table();
+ let crc = 4294967295;
+ for (let i = 0;i < bytes.length; i++)
+ crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
+ return (4294967295 ^ crc) >>> 0;
+};
+var throwNativeGzipValidationError = (reason) => {
+ throw createNamedError(NATIVE_GZIP_VALIDATION_ERROR, `Native gzip produced invalid output: ${reason}`);
+};
+var validateNativeGzip = async (compressed, inputBytes) => {
+ if (compressed.size < 18)
+ throwNativeGzipValidationError("too-short");
+ const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
+ if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
+ throwNativeGzipValidationError("invalid-header");
+ const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
+ if (trailer.getUint32(0, true) !== crc32(inputBytes))
+ throwNativeGzipValidationError("invalid-crc");
+ const inputSize = inputBytes.length >>> 0;
+ if (trailer.getUint32(4, true) !== inputSize)
+ throwNativeGzipValidationError("invalid-size");
+};
+async function gzipCompress(input, isDebug = true, options) {
+ try {
+ const inputBytes = new TextEncoder().encode(input);
+ const compressedStream = new globalThis.CompressionStream("gzip");
+ const writer = compressedStream.writable.getWriter();
+ const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
+ try {
+ await writer.abort(err);
+ } catch {}
+ throw err;
+ });
+ const responsePromise = new Response(compressedStream.readable).blob();
+ const [compressed] = await Promise.all([
+ responsePromise,
+ writePromise
+ ]);
+ await validateNativeGzip(compressed, inputBytes);
+ return compressed;
+ } catch (error) {
+ if (options?.rethrow)
+ throw error;
+ if (isDebug)
+ console.error("Failed to gzip compress data", error);
+ return null;
+ }
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
+class PostHogFetchHttpError extends Error {
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
+ }
+ get status() {
+ return this.response.status;
+ }
+ get retryAfterMs() {
+ try {
+ return parseRetryAfterMs(this.response.headers?.get("retry-after"));
+ } catch {
+ return;
+ }
+ }
+ get bodyReadTimedOut() {
+ return this._bodyReadTimedOut;
+ }
+ get text() {
+ if (!this.responseBodyTextPromise)
+ if (Date.now() >= this.responseBodyDeadline) {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ this.cancelResponseBody(timeoutError);
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
+ } else {
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
+ this.responseBodyTimer = safeSetTimeout(() => {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ reject(timeoutError);
+ this.cancelResponseBody(timeoutError);
+ }, this.responseBodyDeadline - Date.now());
+ });
+ let responseBodyText;
+ try {
+ responseBodyText = Promise.resolve(this.response.text());
+ } catch (error) {
+ responseBodyText = Promise.reject(error);
}
+ this.responseBodyTextPromise = Promise.race([
+ responseBodyText,
+ responseBodyTimeout
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
}
- typeName = undefined;
- }
- if (method) {
- typeName = object;
- methodName = method;
- }
- if (method === "<anonymous>") {
- methodName = undefined;
- functionName = undefined;
- }
- if (functionName === undefined) {
- methodName = methodName || UNKNOWN_FUNCTION;
- functionName = typeName ? `${typeName}.${methodName}` : methodName;
- }
- let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
- const isNative = lineMatch[5] === "native";
- if (filename?.match(/\/[A-Z]:/))
- filename = filename.slice(1);
- if (!filename && lineMatch[5] && !isNative)
- filename = lineMatch[5];
- if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
- filename = PROMISE_FRAME_FILENAME;
- return {
- filename: filename ? decodeURI(filename) : undefined,
- module: undefined,
- function: functionName,
- lineno: _parseIntOrUndefined(lineMatch[3]),
- colno: _parseIntOrUndefined(lineMatch[4]),
- in_app: filenameIsInApp(filename || "", isNative),
- platform
- };
+ return this.responseBodyTextPromise;
}
- if (line.match(FILENAME_MATCH))
- return {
- filename: line,
- platform
- };
+ get json() {
+ return this.text.then((text) => JSON.parse(text));
+ }
+ cancelResponseBody(reason) {
+ clearTimeout(this.responseBodyTimer);
+ if (!this.abortController.signal.aborted)
+ this.abortController.abort(reason);
+ (async () => {
+ try {
+ await this.response.body?.cancel();
+ } catch {}
+ })();
+ }
+}
+
+class PostHogFetchNetworkError extends Error {
+ constructor(error) {
+ super("Network error while fetching PostHog", error instanceof Error ? {
+ cause: error
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+ }
+}
+var applyCallerFeatureFlagOverrides = (target, callerProperties) => {
+ for (const key of Object.keys(callerProperties))
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
+ target[key] = callerProperties[key];
};
-function filenameIsInApp(filename, isNative = false) {
- const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
- return !isInternal && filename !== undefined && !filename.includes("node_modules/");
+async function logFlushError(err) {
+ if (err instanceof PostHogFetchHttpError) {
+ let text = "";
+ try {
+ text = await err.text;
+ } catch {
+ if (err.bodyReadTimedOut)
+ text = "<response body read timed out>";
+ }
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
+ } else
+ console.error("Error while flushing PostHog", err);
+ return Promise.resolve();
}
-function _parseIntOrUndefined(input) {
- return parseInt(input || "", 10) || undefined;
+function isPostHogFetchError(err) {
+ return typeof err == "object" && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));
}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
-var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
-var STACKTRACE_FRAME_LIMIT = 50;
-function reverseAndStripFrames(stack) {
- if (!stack.length)
- return [];
- const localStack = Array.from(stack);
- localStack.reverse();
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
- ...frame,
- filename: frame.filename || getLastStackFrame(localStack).filename,
- function: frame.function || UNKNOWN_FUNCTION
- }));
+function isPostHogFetchNetworkError(err) {
+ return err instanceof PostHogFetchNetworkError;
}
-function getLastStackFrame(arr) {
- return arr[arr.length - 1] || {};
+function isRetryableFlagsFetchError(err) {
+ if (err instanceof PostHogFetchHttpError)
+ return err.status === 502 || err.status === 504;
+ if (!(err instanceof PostHogFetchNetworkError))
+ return false;
+ const cause = err.error;
+ const code = cause?.code ?? cause?.cause?.code;
+ return code !== "ECONNREFUSED";
}
-function createDefaultStackParser() {
- return createStackParser("web:javascript", chromeStackLineParser, geckoStackLineParser);
+var OTLP_MAX_BODY_BYTES = 10485760;
+function byteLengthOf(body) {
+ try {
+ if (typeof body != "string")
+ return body instanceof Uint8Array ? body.byteLength : body.size;
+ if ("u" > typeof Buffer)
+ return Buffer.byteLength(body, STRING_FORMAT);
+ return new TextEncoder().encode(body).length;
+ } catch {
+ return 0;
+ }
}
-function createStackParser(platform, ...parsers) {
- return (stack, skipFirstLines = 0) => {
- const frames = [];
- const lines = stack.split(`
-`);
- for (let i = skipFirstLines;i < lines.length; i++) {
- const line = lines[i];
- if (line.length > 1024)
- continue;
- const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
- if (!cleanedLine.match(/\S*Error: /)) {
- for (const parser of parsers) {
- const frame = parser(cleanedLine, platform);
- if (frame) {
- frames.push(frame);
+function isPostHogFetchContentTooLargeError(err) {
+ return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
+}
+function isPostHogFetchRetryableError(err) {
+ if (err instanceof PostHogFetchHttpError)
+ return err.status === 408 || err.status === 429 || err.status >= 500;
+ return isPostHogFetchNetworkError(err);
+}
+function isPostHogEventProperties(value) {
+ return value !== null && typeof value == "object" && !Array.isArray(value);
+}
+var DEFAULT_QUEUE_ROUTE = "default";
+
+class PostHogCoreStateless {
+ getErrorPropertiesBuilder() {
+ if (!this._errorPropertiesBuilder)
+ this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();
+ return this._errorPropertiesBuilder;
+ }
+ createErrorPropertiesBuilder() {
+ return new ErrorPropertiesBuilder([
+ new ErrorCoercer,
+ new ObjectCoercer,
+ new StringCoercer,
+ new PrimitiveCoercer
+ ], createDefaultStackParser());
+ }
+ getEvaluationRuntime() {}
+ constructor(apiKey, options = {}) {
+ this.flushPromise = null;
+ this.pendingFlushPromise = null;
+ this.flushPromises = new Set;
+ this._dequeuedMessagesCount = 0;
+ this.shutdownPromise = null;
+ this.promiseQueue = new PromiseQueue;
+ this._events = new SimpleEventEmitter;
+ this._isInitialized = false;
+ const normalizedApiKey = typeof apiKey == "string" ? apiKey.trim() : "";
+ const normalizedHost = typeof options.host == "string" ? options.host.trim() : "";
+ const missingApiKey = !normalizedApiKey;
+ this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
+ if (missingApiKey)
+ this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");
+ this.apiKey = normalizedApiKey;
+ this.host = removeTrailingSlash(normalizedHost || "https://us.i.posthog.com");
+ this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
+ this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
+ this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);
+ this.flushInterval = options.flushInterval ?? 1e4;
+ this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
+ this.defaultOptIn = options.defaultOptIn ?? true;
+ this.disableSurveys = options.disableSurveys ?? false;
+ this._retryOptions = {
+ retryCount: options.fetchRetryCount ?? 3,
+ retryDelay: options.fetchRetryDelay ?? 3000,
+ retryCheck: isPostHogFetchRetryableError
+ };
+ this.requestTimeout = options.requestTimeout ?? 1e4;
+ this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
+ this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
+ this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
+ this.disableGeoip = options.disableGeoip ?? true;
+ this.disabled = (options.disabled ?? false) || missingApiKey;
+ this.historicalMigration = options?.historicalMigration ?? false;
+ this._initPromise = Promise.resolve();
+ this._isInitialized = true;
+ this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
+ if (options?.evaluationEnvironments && !options?.evaluationContexts)
+ this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");
+ this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
+ }
+ logMsgIfDebug(fn) {
+ if (this.isDebug)
+ fn();
+ }
+ wrap(fn) {
+ if (this.disabled)
+ return void this._logger.warn("The client is disabled");
+ if (this._isInitialized)
+ return fn();
+ this._initPromise.then(() => fn());
+ }
+ getCommonEventProperties() {
+ return {
+ $lib: this.getLibraryId(),
+ $lib_version: this.getLibraryVersion()
+ };
+ }
+ get optedOut() {
+ return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
+ }
+ async optIn() {
+ this.wrap(() => {
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
+ });
+ }
+ async optOut() {
+ this.wrap(() => {
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
+ });
+ }
+ on(event, cb) {
+ return this._events.on(event, cb);
+ }
+ debug(enabled = true) {
+ this.removeDebugCallback?.();
+ if (enabled) {
+ const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
+ this.removeDebugCallback = () => {
+ removeDebugCallback();
+ this.removeDebugCallback = undefined;
+ };
+ }
+ }
+ get isDebug() {
+ return !!this.removeDebugCallback;
+ }
+ get isDisabled() {
+ return this.disabled;
+ }
+ buildPayload(payload) {
+ const userProperties = payload.properties || {};
+ let properties = {
+ ...userProperties,
+ ...this.getCommonEventProperties()
+ };
+ applyCallerFeatureFlagOverrides(properties, userProperties);
+ if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
+ properties = minimizeFlagCalledEventProperties(properties);
+ return {
+ distinct_id: payload.distinct_id,
+ event: payload.event,
+ properties
+ };
+ }
+ isMinimalFlagCalledEventsEnabled() {
+ return false;
+ }
+ addPendingPromise(promise) {
+ return this.promiseQueue.add(promise);
+ }
+ identifyStateless(distinctId, properties, options) {
+ this.wrap(() => {
+ const payload = {
+ ...this.buildPayload({
+ distinct_id: distinctId,
+ event: "$identify",
+ properties
+ })
+ };
+ this.enqueue("identify", payload, options);
+ });
+ }
+ async identifyStatelessImmediate(distinctId, properties, options) {
+ const payload = {
+ ...this.buildPayload({
+ distinct_id: distinctId,
+ event: "$identify",
+ properties
+ })
+ };
+ await this.sendImmediate("identify", payload, options);
+ }
+ captureStateless(distinctId, event, properties, options) {
+ this.wrap(() => {
+ const payload = this.buildPayload({
+ distinct_id: distinctId,
+ event,
+ properties
+ });
+ this.enqueue("capture", payload, options);
+ });
+ }
+ async captureStatelessImmediate(distinctId, event, properties, options) {
+ const payload = this.buildPayload({
+ distinct_id: distinctId,
+ event,
+ properties
+ });
+ await this.sendImmediate("capture", payload, options);
+ }
+ aliasStateless(alias, distinctId, properties, options) {
+ this.wrap(() => {
+ const payload = this.buildPayload({
+ event: "$create_alias",
+ distinct_id: distinctId,
+ properties: {
+ ...properties || {},
+ distinct_id: distinctId,
+ alias
+ }
+ });
+ this.enqueue("alias", payload, options);
+ });
+ }
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
+ const payload = this.buildPayload({
+ event: "$create_alias",
+ distinct_id: distinctId,
+ properties: {
+ ...properties || {},
+ distinct_id: distinctId,
+ alias
+ }
+ });
+ await this.sendImmediate("alias", payload, options);
+ }
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
+ this.wrap(() => {
+ const payload = this.buildPayload({
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
+ event: "$groupidentify",
+ properties: {
+ $group_type: groupType,
+ $group_key: groupKey,
+ $group_set: groupProperties || {},
+ ...eventProperties || {}
+ }
+ });
+ this.enqueue("capture", payload, options);
+ });
+ }
+ async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
+ const payload = this.buildPayload({
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
+ event: "$groupidentify",
+ properties: {
+ $group_type: groupType,
+ $group_key: groupKey,
+ $group_set: groupProperties || {},
+ ...eventProperties || {}
+ }
+ });
+ await this.sendImmediate("capture", payload, options);
+ }
+ async getRemoteConfig() {
+ await this._initPromise;
+ let host = this.host;
+ if (host === "https://us.i.posthog.com")
+ host = "https://us-assets.i.posthog.com";
+ else if (host === "https://eu.i.posthog.com")
+ host = "https://eu-assets.i.posthog.com";
+ const url = `${host}/array/${this.apiKey}/config`;
+ const fetchOptions = {
+ method: "GET",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json"
+ }
+ };
+ return this.fetchWithRetry(url, fetchOptions, {
+ type: "required",
+ consume: (response) => response.json()
+ }, {
+ retryCount: 0
+ }, this.remoteConfigRequestTimeoutMs).catch((error) => {
+ this._logger.error("Remote config could not be loaded", error);
+ this._events.emit("error", error);
+ });
+ }
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {
+ await this._initPromise;
+ const configParam = fetchConfig ? "&config=true" : "";
+ const url = `${this.host}/flags/?v=2${configParam}`;
+ const requestData = {
+ token: this.apiKey,
+ distinct_id: distinctId,
+ groups,
+ person_properties: personProperties,
+ group_properties: groupProperties,
+ ...extraPayload
+ };
+ if (personProperties.$device_id)
+ requestData.$device_id = personProperties.$device_id;
+ if (this.evaluationContexts && this.evaluationContexts.length > 0)
+ requestData.evaluation_contexts = this.evaluationContexts;
+ const evaluationRuntime = this.getEvaluationRuntime();
+ if (evaluationRuntime)
+ requestData.evaluation_runtime = evaluationRuntime;
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify(requestData)
+ };
+ this._logger.info("Flags URL", url);
+ return this.fetchWithRetry(url, fetchOptions, {
+ type: "required",
+ consume: (response) => response.json()
+ }, {
+ retryCount: this.featureFlagsRequestMaxRetries,
+ retryCheck: isRetryableFlagsFetchError
+ }, this.featureFlagsRequestTimeoutMs).then((response) => ({
+ success: true,
+ response: normalizeFlagsResponse(response)
+ })).catch((error) => {
+ this._events.emit("error", error);
+ return {
+ success: false,
+ error: this.categorizeRequestError(error)
+ };
+ });
+ }
+ categorizeRequestError(error) {
+ if (error instanceof PostHogFetchHttpError)
+ return {
+ type: "api_error",
+ statusCode: error.status
+ };
+ if (error instanceof PostHogFetchNetworkError) {
+ const cause = error.error;
+ if (cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError"))
+ return {
+ type: "timeout"
+ };
+ return {
+ type: "connection_error"
+ };
+ }
+ return {
+ type: "unknown_error"
+ };
+ }
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
+ await this._initPromise;
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
+ if (flagDetailResponse === undefined)
+ return {
+ response: undefined,
+ requestId: undefined
+ };
+ let response = getFeatureFlagValue(flagDetailResponse.response);
+ if (response === undefined)
+ response = false;
+ return {
+ response,
+ requestId: flagDetailResponse.requestId
+ };
+ }
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
+ await this._initPromise;
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
+ key
+ ]);
+ if (flagsResponse === undefined)
+ return;
+ const featureFlags = flagsResponse.flags;
+ const flagDetail = featureFlags[key];
+ return {
+ response: flagDetail,
+ requestId: flagsResponse.requestId,
+ evaluatedAt: flagsResponse.evaluatedAt
+ };
+ }
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
+ await this._initPromise;
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
+ key
+ ]);
+ if (!payloads)
+ return;
+ const response = payloads[key];
+ if (response === undefined)
+ return null;
+ return response;
+ }
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
+ return payloads;
+ }
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
+ }
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
+ if (!featureFlagDetails)
+ return {
+ flags: undefined,
+ payloads: undefined,
+ requestId: undefined
+ };
+ return {
+ flags: featureFlagDetails.featureFlags,
+ payloads: featureFlagDetails.featureFlagPayloads,
+ requestId: featureFlagDetails.requestId
+ };
+ }
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
+ await this._initPromise;
+ const extraPayload = {
+ geoip_disable: disableGeoip ?? this.disableGeoip
+ };
+ if (flagKeysToEvaluate)
+ extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
+ const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
+ if (!result.success)
+ return;
+ const flagsResponse = result.response;
+ if (flagsResponse.errorsWhileComputingFlags)
+ console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");
+ if (flagsResponse.quotaLimited?.includes("feature_flags")) {
+ console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
+ return {
+ flags: {},
+ featureFlags: {},
+ featureFlagPayloads: {},
+ requestId: flagsResponse?.requestId,
+ quotaLimited: flagsResponse.quotaLimited
+ };
+ }
+ return flagsResponse;
+ }
+ async getSurveysStateless() {
+ await this._initPromise;
+ if (this.disabled)
+ return [];
+ if (this.disableSurveys === true) {
+ this._logger.info("Loading surveys is disabled.");
+ return [];
+ }
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
+ const fetchOptions = {
+ method: "GET",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json"
+ }
+ };
+ const response = await this.fetchWithRetry(url, fetchOptions, {
+ type: "required",
+ consume: (response) => {
+ if (response.status !== 200 || !response.json) {
+ const msg = `Surveys API could not be loaded: ${response.status}`;
+ const error = new Error(msg);
+ this._logger.error(error);
+ this._events.emit("error", new Error(msg));
+ return Promise.resolve(undefined);
+ }
+ return response.json();
+ }
+ }).catch((error) => {
+ this._logger.error("Surveys API could not be loaded", error);
+ this._events.emit("error", error);
+ });
+ const newSurveys = response?.surveys;
+ if (newSurveys)
+ this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
+ return newSurveys ?? [];
+ }
+ get props() {
+ if (!this._props)
+ this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
+ return this._props || {};
+ }
+ set props(val) {
+ this._props = val;
+ }
+ async register(properties) {
+ this.wrap(() => {
+ this.props = {
+ ...this.props,
+ ...properties
+ };
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
+ });
+ }
+ async unregister(property) {
+ this.wrap(() => {
+ delete this.props[property];
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
+ });
+ }
+ processBeforeEnqueue(message) {
+ return message;
+ }
+ async flushStorage() {}
+ getQueueRouteKey(_message) {
+ return DEFAULT_QUEUE_ROUTE;
+ }
+ persistedQueueKeyForRoute(_route) {
+ return types_PostHogPersistedProperty.Queue;
+ }
+ getActiveQueueRoutes() {
+ return [
+ DEFAULT_QUEUE_ROUTE
+ ];
+ }
+ getRouteQueue(route) {
+ return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
+ }
+ enqueue(type, _message, options, explicitRoute) {
+ this.wrap(() => {
+ if (this.optedOut)
+ return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
+ let message = this.prepareMessage(_message, options);
+ message = this.processBeforeEnqueue(message);
+ if (message === null)
+ return;
+ message = this.normalizeMessage(message);
+ const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
+ const queue = this.getPersistedProperty(queueKey) || [];
+ if (queue.length >= this.maxQueueSize) {
+ queue.shift();
+ this._logger.warn("Queue is full, the oldest event is dropped.");
+ }
+ queue.push({
+ message
+ });
+ this.setPersistedProperty(queueKey, queue);
+ this._events.emit(type, message);
+ if (queue.length >= this.flushAt)
+ this.flushBackground();
+ if (this.flushInterval && !this._flushTimer)
+ this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
+ });
+ }
+ async sendImmediate(type, _message, options, explicitRoute) {
+ if (this.disabled)
+ return void this._logger.warn("The client is disabled");
+ if (!this._isInitialized)
+ await this._initPromise;
+ if (this.optedOut)
+ return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
+ let message = this.prepareMessage(_message, options);
+ message = this.processBeforeEnqueue(message);
+ if (message === null)
+ return;
+ message = this.normalizeMessage(message);
+ try {
+ await this.sendBatch([
+ message
+ ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
+ } catch (err) {
+ this._events.emit("error", err);
+ }
+ }
+ normalizeMessage(message) {
+ const { type: _type, library, library_version, ...sanitizedMessage } = message;
+ let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
+ if (library !== undefined && properties?.$lib === undefined)
+ properties = {
+ ...properties || {},
+ $lib: library
+ };
+ if (library_version !== undefined && properties?.$lib_version === undefined)
+ properties = {
+ ...properties || {},
+ $lib_version: library_version
+ };
+ if (properties)
+ sanitizedMessage.properties = properties;
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
+ return sanitizedMessage;
+ }
+ normalizeTimestampForWire(timestamp) {
+ const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
+ if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
+ return timestamp;
+ const normalized = parsedTimestamp.toISOString();
+ const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
+ }
+ prepareMessage(_message, options) {
+ const message = {
+ ..._message,
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
+ uuid: getEventUuid(options?.uuid, uuidv7)
+ };
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
+ if (addGeoipDisableProperty) {
+ if (!isPostHogEventProperties(message.properties))
+ message.properties = {};
+ message.properties["$geoip_disable"] = true;
+ }
+ if (message.distinctId) {
+ message.distinct_id = message.distinctId;
+ delete message.distinctId;
+ }
+ return message;
+ }
+ clearFlushTimer() {
+ if (this._flushTimer) {
+ clearTimeout(this._flushTimer);
+ this._flushTimer = undefined;
+ }
+ }
+ flushBackground() {
+ if (this.pendingFlushPromise)
+ return;
+ this.flushAutomatic().catch(async (err) => {
+ await logFlushError(err);
+ });
+ }
+ flushAutomatic() {
+ return this.flush();
+ }
+ async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
+ const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
+ let iteration = 0;
+ while (true) {
+ const promises = this.promiseQueue.getPromises([
+ ...ignoredPendingPromises,
+ ...this.flushPromises
+ ], maxPromiseId);
+ if (promises.length === 0)
+ return;
+ if (iteration > 0)
+ this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
+ await Promise.all(promises.map((promise) => promise.catch(() => {})));
+ iteration++;
+ }
+ }
+ flushWithPendingPromises() {
+ return this.flushInternal(true);
+ }
+ flush() {
+ return this.flushInternal(false);
+ }
+ flushInternal(waitForPendingPromises) {
+ if (this.disabled)
+ return Promise.resolve();
+ if (!waitForPendingPromises && this.pendingFlushPromise)
+ return this.pendingFlushPromise;
+ const previousFlushPromise = this.flushPromise;
+ const maxPromiseId = this.promiseQueue.maxId;
+ const nextFlushPromise = Promise.resolve().then(() => {
+ if (waitForPendingPromises)
+ return this.waitForPendingPromises(maxPromiseId, [
+ previousFlushPromise,
+ nextFlushPromise
+ ]);
+ }).then(() => allSettled([
+ previousFlushPromise
+ ])).then(() => {
+ if (this.pendingFlushPromise === nextFlushPromise)
+ this.pendingFlushPromise = null;
+ return this._flush();
+ });
+ this.pendingFlushPromise = nextFlushPromise;
+ this.flushPromise = nextFlushPromise;
+ this.flushPromises.add(nextFlushPromise);
+ this.addPendingPromise(nextFlushPromise);
+ allSettled([
+ nextFlushPromise
+ ]).then(() => {
+ this.flushPromises.delete(nextFlushPromise);
+ if (this.pendingFlushPromise === nextFlushPromise)
+ this.pendingFlushPromise = null;
+ if (this.flushPromise === nextFlushPromise)
+ this.flushPromise = null;
+ });
+ return nextFlushPromise;
+ }
+ getCustomHeaders() {
+ const customUserAgent = this.getCustomUserAgent();
+ const headers = {};
+ if (customUserAgent && customUserAgent !== "")
+ headers["User-Agent"] = customUserAgent;
+ return headers;
+ }
+ compressPayload(payload) {
+ return gzipCompress(payload, this.isDebug);
+ }
+ getBatchEndpointPath(_route) {
+ return "/batch/";
+ }
+ async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
+ const data = {
+ api_key: this.apiKey,
+ batch: batchMessages.map((message) => {
+ if (!message)
+ return message;
+ const timestamp = this.normalizeTimestampForWire(message.timestamp);
+ return timestamp === message.timestamp ? message : {
+ ...message,
+ timestamp
+ };
+ }),
+ sent_at: currentISOTime()
+ };
+ if (this.historicalMigration)
+ data.historical_migration = true;
+ const payload = safeJsonStringify(data);
+ const url = `${this.host}${this.getBatchEndpointPath(route)}`;
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json",
+ ...gzippedPayload !== null && {
+ "Content-Encoding": "gzip"
+ }
+ },
+ body: gzippedPayload || payload
+ };
+ await this.fetchWithRetry(url, fetchOptions, {
+ type: "successful-write"
+ }, retryOptions);
+ }
+ async _flush() {
+ this.clearFlushTimer();
+ await this._initPromise;
+ const routes = this.getActiveQueueRoutes();
+ if (!routes.some((route) => this.getRouteQueue(route).length > 0))
+ return;
+ const sentMessages = [];
+ let firstError;
+ for (const route of routes)
+ try {
+ await this._flushRoute(route, sentMessages);
+ } catch (err) {
+ if (firstError === undefined)
+ firstError = err;
+ }
+ if (firstError !== undefined)
+ throw firstError;
+ this._events.emit("flush", sentMessages);
+ }
+ async _flushRoute(route, sentMessages) {
+ const queueKey = this.persistedQueueKeyForRoute(route);
+ let queue = this.getPersistedProperty(queueKey) || [];
+ if (!queue.length)
+ return;
+ const originalQueueLength = queue.length;
+ let sentFromRoute = 0;
+ while (queue.length > 0 && sentFromRoute < originalQueueLength) {
+ const batchItems = queue.slice(0, this.maxBatchSize);
+ const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
+ const persistQueueChange = async () => {
+ const refreshedQueue = this.getPersistedProperty(queueKey) || [];
+ const remainingBatchItems = [
+ ...batchItems
+ ];
+ const newQueue = refreshedQueue.filter((item) => {
+ const itemUuid = item.message?.uuid;
+ const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
+ if (batchItemIndex === -1)
+ return true;
+ remainingBatchItems.splice(batchItemIndex, 1);
+ return false;
+ });
+ this.setPersistedProperty(queueKey, newQueue);
+ queue = newQueue;
+ this._dequeuedMessagesCount += batchItems.length;
+ await this.flushStorage();
+ };
+ const retryOptions = {
+ retryCheck: (err) => {
+ if (isPostHogFetchContentTooLargeError(err))
+ return false;
+ return isPostHogFetchRetryableError(err);
+ }
+ };
+ try {
+ await this.sendBatch(batchMessages, retryOptions, route);
+ } catch (err) {
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
+ this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
+ continue;
+ }
+ if (!(err instanceof PostHogFetchNetworkError))
+ await persistQueueChange();
+ this._events.emit("error", err);
+ throw err;
+ }
+ await persistQueueChange();
+ sentMessages.push(...batchMessages);
+ sentFromRoute += batchMessages.length;
+ }
+ }
+ async _sendOtlpBatch({ path, auth, payload }) {
+ if (this.disabled)
+ return {
+ kind: "fatal",
+ error: new Error("The client is disabled")
+ };
+ let serialized;
+ try {
+ serialized = JSON.stringify(payload);
+ } catch (error) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Could not serialize a ${path} batch; reporting it as too large`, error));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const payloadBytes = byteLengthOf(serialized);
+ if (payloadBytes > OTLP_MAX_BODY_BYTES) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Not sending a ${path} batch of ${payloadBytes} bytes: the endpoint accepts at most ${OTLP_MAX_BODY_BYTES}`));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const url = auth === "bearer" ? `${this.host}/i/v1/${path}` : `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
+ const body = gzippedPayload || serialized;
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json",
+ ...auth === "bearer" && {
+ Authorization: `Bearer ${this.apiKey}`
+ },
+ ...gzippedPayload !== null && {
+ "Content-Encoding": "gzip"
+ }
+ },
+ body
+ };
+ try {
+ await this.fetchWithRetry(url, fetchOptions, {
+ type: "successful-write"
+ }, {
+ retryCheck: (err) => {
+ if (isPostHogFetchContentTooLargeError(err))
+ return false;
+ if (err instanceof PostHogFetchHttpError && err.retryAfterMs !== undefined)
+ return false;
+ return isPostHogFetchRetryableError(err);
+ }
+ });
+ return {
+ kind: "ok"
+ };
+ } catch (err) {
+ if (isPostHogFetchContentTooLargeError(err))
+ return {
+ kind: "too-large"
+ };
+ if (isPostHogFetchRetryableError(err)) {
+ const retryAfterMs = err instanceof PostHogFetchHttpError ? err.retryAfterMs : undefined;
+ return {
+ kind: "retry-later",
+ error: err,
+ ...retryAfterMs !== undefined && {
+ retryAfterMs
+ }
+ };
+ }
+ return {
+ kind: "fatal",
+ error: err
+ };
+ }
+ }
+ async _sendLogsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "logs",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendMetricsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "metrics",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendTracesBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "traces",
+ auth: "bearer",
+ payload
+ });
+ }
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
+ const body = options.body ? options.body : "";
+ const reqByteLength = byteLengthOf(body);
+ const retriableOptions = {
+ ...this._retryOptions,
+ ...retryOptions
+ };
+ let attempt = 0;
+ return await retriable(async () => {
+ attempt++;
+ const ctrl = new AbortController;
+ const timeoutMs = requestTimeout ?? this.requestTimeout;
+ const requestDeadline = Date.now() + timeoutMs;
+ let timer;
+ const deadline = new Promise((_resolve, reject) => {
+ timer = safeSetTimeout(() => {
+ const timeoutError = createNamedError("AbortError", `Request timed out after ${timeoutMs}ms`);
+ reject(timeoutError);
+ ctrl.abort(timeoutError);
+ }, timeoutMs);
+ });
+ let res;
+ let responseAccepted = false;
+ let cancellation;
+ const cancelBody = () => cancellation ??= (async () => {
+ try {
+ await res?.body?.cancel();
+ } catch {}
+ })();
+ try {
+ let fetchPromise;
+ try {
+ fetchPromise = this.fetch(url, {
+ signal: ctrl.signal,
+ ...options
+ });
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ fetchPromise.then((lateResponse) => {
+ if (ctrl.signal.aborted && !responseAccepted)
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
+ }).catch(() => {});
+ try {
+ res = await Promise.race([
+ fetchPromise,
+ deadline
+ ]);
+ responseAccepted = true;
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ const isNoCors = options.mode === "no-cors";
+ const maxSuccessStatus = responseHandling.type === "successful-write" ? 300 : 400;
+ if (!isNoCors && (res.status < 200 || res.status >= maxSuccessStatus))
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
+ if (responseHandling.type === "successful-write") {
+ try {
+ await Promise.race([
+ cancelBody(),
+ deadline
+ ]);
+ } catch {}
+ return;
+ }
+ try {
+ return await Promise.race([
+ responseHandling.consume(res),
+ deadline
+ ]);
+ } catch (e) {
+ if (ctrl.signal.aborted)
+ throw new PostHogFetchNetworkError(e);
+ throw e;
+ }
+ } finally {
+ clearTimeout(timer);
+ if (ctrl.signal.aborted && res)
+ cancelBody();
+ }
+ }, {
+ ...retriableOptions,
+ retryCheck: (error) => {
+ const shouldRetry = retriableOptions.retryCheck(error);
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
+ error.cancelResponseBody();
+ return shouldRetry;
+ }
+ });
+ }
+ async _shutdown(shutdownTimeoutMs = 30000) {
+ await this._initPromise;
+ let hasTimedOut = false;
+ this.clearFlushTimer();
+ if (this.disabled)
+ return;
+ const doShutdown = async () => {
+ try {
+ await this.promiseQueue.join();
+ while (true) {
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
+ if (!hasQueuedEvents)
+ break;
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
+ await this.flush();
+ if (hasTimedOut)
+ break;
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
break;
}
}
- if (frames.length >= STACKTRACE_FRAME_LIMIT)
- break;
+ } catch (e) {
+ if (!isPostHogFetchError(e))
+ throw e;
+ await logFlushError(e);
}
- }
- return reverseAndStripFrames(frames);
- };
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
-class ErrorCoercer {
- match(err) {
- return isError(err);
- }
- coerce(err, ctx) {
- const stack = this.getStack(err);
- const synthetic = stack === undefined;
- return {
- type: this.getType(err),
- value: this.getMessage(err, ctx),
- stack: stack ?? ctx.syntheticException?.stack,
- cause: err.cause ? ctx.next(err.cause) : undefined,
- synthetic
- };
- }
- getType(err) {
- return err.name || err.constructor.name;
- }
- getMessage(err, _ctx) {
- const message = err.message;
- if (message.error && typeof message.error.message == "string")
- return String(message.error.message);
- return String(message);
- }
- getStack(err) {
- return err.stacktrace || err.stack || undefined;
- }
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
-var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
-
-class StringCoercer {
- match(input) {
- return typeof input == "string";
- }
- coerce(input, ctx) {
- const [type, value] = this.getInfos(input);
- return {
- type: type ?? "Error",
- value: value ?? input,
- stack: ctx.syntheticException?.stack,
- synthetic: true
};
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
+ shutdownTimeoutMs
+ });
+ hasTimedOut = true;
+ });
}
- getInfos(candidate) {
- let type = "Error";
- let value = candidate;
- const groups = candidate.match(ERROR_TYPES_PATTERN);
- if (groups) {
- type = groups[1];
- value = groups[2];
- }
- return [
- type,
- value
- ];
+ async shutdown(shutdownTimeoutMs = 30000) {
+ if (this.shutdownPromise)
+ this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
+ else
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
+ this.shutdownPromise = null;
+ });
+ return this.shutdownPromise;
}
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
-var severityLevels = [
- "fatal",
- "error",
- "warning",
- "log",
- "info",
- "debug"
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.mjs
+var NULL_VALUES_ALLOWED_OPERATORS = [
+ "is_not",
+ "is_set"
];
+var LONG_SCALE = 1152921504606847000;
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
-function extractExceptionKeysForMessage(err, maxLength = 40) {
- const keys = Object.keys(err);
- keys.sort();
- if (!keys.length)
- return "[object has no keys]";
- for (let i = keys.length;i > 0; i--) {
- const serialized = keys.slice(0, i).join(", ");
- if (!(serialized.length > maxLength)) {
- if (i === keys.length)
- return serialized;
- return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
- }
+class InconclusiveMatchError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = this.constructor.name;
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
}
- return "";
}
-
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
-class ObjectCoercer {
- match(candidate) {
- return typeof candidate == "object" && candidate !== null;
- }
- coerce(candidate, ctx) {
- const errorProperty = this.getErrorPropertyFromObject(candidate);
- if (errorProperty)
- return ctx.apply(errorProperty);
- return {
- type: this.getType(candidate),
- value: this.getValue(candidate),
- stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
- level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
- synthetic: true
- };
- }
- getType(err) {
- if (isEvent(err))
- return err.constructor.name;
- const name = "name" in err ? err.name : undefined;
- return isString(name) && !isEmptyString(name) ? name : "Error";
- }
- getValue(err) {
- if ("name" in err && typeof err.name == "string") {
- let message = `'${err.name}' captured as exception`;
- if ("message" in err && typeof err.message == "string")
- message += ` with message: '${err.message}'`;
- return message;
- }
- if ("message" in err && typeof err.message == "string")
- return err.message;
- const className = this.getObjectClassName(err);
- const keys = extractExceptionKeysForMessage(err);
- return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
+function isTruthyOrFalsyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return true;
+ if (typeof value == "string") {
+ const lowercaseValue = value.toLowerCase();
+ return lowercaseValue === "true" || lowercaseValue === "false";
}
- isSeverityLevel(x) {
- return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyOrFalsyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function isTruthyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return value;
+ if (typeof value == "string")
+ return value.toLowerCase() === "true";
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function assertUnicodeScalarString(value) {
+ for (let index = 0;index < value.length; index++) {
+ const unit = value.charCodeAt(index);
+ if (unit >= 55296 && unit <= 56319) {
+ const next = value.charCodeAt(index + 1);
+ if (index + 1 >= value.length || next < 56320 || next > 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ index++;
+ } else if (unit >= 56320 && unit <= 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ }
+}
+function assertJsonRepresentable(value, seen = new Set) {
+ if (value === null || typeof value == "boolean")
+ return;
+ if (typeof value == "string")
+ return void assertUnicodeScalarString(value);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot represent non-finite number ${value} like the flags service`);
+ return;
}
- getStack(candidate) {
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular array during local evaluation");
+ seen.add(value);
try {
- if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
- return candidate.stacktrace;
- return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
- } catch {
- return;
+ for (let index = 0;index < value.length; index++)
+ if (index in value)
+ assertJsonRepresentable(value[index], seen);
+ } finally {
+ seen.delete(value);
}
+ return;
}
- getErrorPropertyFromObject(obj) {
- for (const prop in obj)
- if (Object.prototype.hasOwnProperty.call(obj, prop)) {
- const value = obj[prop];
- if (isError(value))
- return value;
- }
- }
- getObjectClassName(obj) {
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot represent a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular object during local evaluation");
+ seen.add(value);
try {
- const prototype = Object.getPrototypeOf(obj);
- return prototype ? prototype.constructor.name : undefined;
- } catch (e) {
- return;
+ for (const key of Object.keys(value)) {
+ assertUnicodeScalarString(key);
+ assertJsonRepresentable(value[key], seen);
+ }
+ } finally {
+ seen.delete(value);
}
+ return;
}
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
-class EventCoercer {
- match(err) {
- return isEvent(err);
- }
- coerce(evt, ctx) {
- const constructorName = evt.constructor.name;
- return {
- type: constructorName,
- value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
- stack: ctx.syntheticException?.stack,
- synthetic: true
- };
- }
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
-class PrimitiveCoercer {
- match(candidate) {
- return isPrimitive(candidate);
- }
- coerce(value, ctx) {
- return {
- type: "Error",
- value: `Primitive value captured as exception: ${String(value)}`,
- stack: ctx.syntheticException?.stack,
- synthetic: true
- };
- }
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
-class ReduceableCache {
- constructor(_maxSize) {
- this._maxSize = _maxSize;
- this._cache = new Map;
- }
- get(key) {
- const value = this._cache.get(key);
- if (value === undefined)
- return;
- this._cache.delete(key);
- this._cache.set(key, value);
- return value;
+ throw new InconclusiveMatchError(`Cannot represent ${typeof value} like the flags service`);
+}
+function compareJsonObjectKeys(left, right) {
+ let leftIndex = 0;
+ let rightIndex = 0;
+ while (leftIndex < left.length && rightIndex < right.length) {
+ const leftUnit = left.charCodeAt(leftIndex);
+ const rightUnit = right.charCodeAt(rightIndex);
+ const leftIsHighSurrogate = leftUnit >= 55296 && leftUnit <= 56319;
+ const rightIsHighSurrogate = rightUnit >= 55296 && rightUnit <= 56319;
+ const leftNext = leftIsHighSurrogate ? left.charCodeAt(leftIndex + 1) : 0;
+ const rightNext = rightIsHighSurrogate ? right.charCodeAt(rightIndex + 1) : 0;
+ const leftCodePoint = leftIsHighSurrogate ? (leftUnit - 55296) * 1024 + leftNext - 56320 + 65536 : leftUnit;
+ const rightCodePoint = rightIsHighSurrogate ? (rightUnit - 55296) * 1024 + rightNext - 56320 + 65536 : rightUnit;
+ if (leftCodePoint !== rightCodePoint)
+ return leftCodePoint - rightCodePoint;
+ leftIndex += leftIsHighSurrogate ? 2 : 1;
+ rightIndex += rightIsHighSurrogate ? 2 : 1;
+ }
+ return left.length - right.length;
+}
+function serializeJsonValue(value, seen = new Set) {
+ if (value === null)
+ return "null";
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return JSON.stringify(value);
}
- set(key, value) {
- this._cache.set(key, value);
+ if (typeof value == "boolean")
+ return value ? "true" : "false";
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot stringify non-finite number ${value} like the flags service`);
+ if (Number.isInteger(value))
+ throw new InconclusiveMatchError(`Cannot distinguish integer ${value} from an integral JSON float during local evaluation`);
+ return String(value);
+ }
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular array during local evaluation");
+ seen.add(value);
+ try {
+ const items = [];
+ for (let index = 0;index < value.length; index++)
+ items.push(index in value ? serializeJsonValue(value[index], seen) : "null");
+ return `[${items.join(",")}]`;
+ } finally {
+ seen.delete(value);
+ }
}
- reduce() {
- while (this._cache.size >= this._maxSize) {
- const value = this._cache.keys().next().value;
- if (value)
- this._cache.delete(value);
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot stringify a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular object during local evaluation");
+ seen.add(value);
+ try {
+ const keys = Object.keys(value);
+ keys.forEach(assertUnicodeScalarString);
+ return `{${keys.sort(compareJsonObjectKeys).map((key) => `${JSON.stringify(key)}:${serializeJsonValue(value[key], seen)}`).join(",")}}`;
+ } finally {
+ seen.delete(value);
}
}
+ throw new InconclusiveMatchError(`Cannot stringify ${typeof value} like the flags service`);
}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
-var EXCEPTION_STEP_INTERNAL_FIELDS = {
- MESSAGE: "$message",
- TIMESTAMP: "$timestamp"
-};
-var RESERVED_EXCEPTION_STEP_KEYS = new Set([
- EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
- EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
-]);
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
-function getInjectedReleaseId() {
- const injected = globalThis._posthogReleaseId;
- return typeof injected == "string" && injected.length > 0 ? injected : undefined;
-}
-// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
-class PostHogFetchHttpError extends Error {
- constructor(response, reqByteLength, responseBodyDeadline, abortController) {
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
- }
- get status() {
- return this.response.status;
- }
- get bodyReadTimedOut() {
- return this._bodyReadTimedOut;
+function exactMatchString(value) {
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return value;
}
- get text() {
- if (!this.responseBodyTextPromise)
- if (Date.now() >= this.responseBodyDeadline) {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- this.cancelResponseBody(timeoutError);
- this.responseBodyTextPromise = Promise.reject(timeoutError);
- } else {
- const responseBodyTimeout = new Promise((_resolve, reject) => {
- this.responseBodyTimer = safeSetTimeout(() => {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- reject(timeoutError);
- this.cancelResponseBody(timeoutError);
- }, this.responseBodyDeadline - Date.now());
- });
- let responseBodyText;
- try {
- responseBodyText = Promise.resolve(this.response.text());
- } catch (error) {
- responseBodyText = Promise.reject(error);
- }
- this.responseBodyTextPromise = Promise.race([
- responseBodyText,
- responseBodyTimeout
- ]).finally(() => clearTimeout(this.responseBodyTimer));
- }
- return this.responseBodyTextPromise;
+ return serializeJsonValue(value);
+}
+function isValidRegex(regex) {
+ try {
+ new RegExp(regex);
+ return true;
+ } catch {
+ return false;
}
- get json() {
- return this.text.then((text) => JSON.parse(text));
+}
+function asciiLowercase(value) {
+ return String(value).replace(/[A-Z]/g, (character) => character.toLowerCase());
+}
+function parseSemverNumericIdentifier(part, raw, parsingPolicy) {
+ if (!/^\d+$/.test(part) || parsingPolicy === "strict" && part.length > 1 && part[0] === "0")
+ throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
+ return parseInt(part, 10);
+}
+function parseFeatureFlagSemver(value, parsingPolicy = "strict") {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const baseVersion = text.split("-")[0].split("+")[0];
+ if (!baseVersion || baseVersion.startsWith("."))
+ throw new InconclusiveMatchError(`Invalid semver: ${value}`);
+ const parts = baseVersion.split(".");
+ const parsePart = (part) => {
+ if (part === undefined || part === "")
+ return 0;
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
+ };
+ return [
+ parsePart(parts[0]),
+ parsePart(parts[1]),
+ parsePart(parts[2])
+ ];
+}
+function compareSemverTuples(a, b) {
+ for (let i = 0;i < 3; i++) {
+ if (a[i] < b[i])
+ return -1;
+ if (a[i] > b[i])
+ return 1;
}
- cancelResponseBody(reason) {
- clearTimeout(this.responseBodyTimer);
- if (!this.abortController.signal.aborted)
- this.abortController.abort(reason);
- (async () => {
+ return 0;
+}
+function computeTildeBounds(value, parsingPolicy) {
+ const parsed = parseFeatureFlagSemver(value, parsingPolicy);
+ return {
+ lower: [
+ parsed[0],
+ parsed[1],
+ parsed[2]
+ ],
+ upper: [
+ parsed[0],
+ parsed[1] + 1,
+ 0
+ ]
+ };
+}
+function computeCaretBounds(value, parsingPolicy) {
+ const [major, minor, patch] = parseFeatureFlagSemver(value, parsingPolicy);
+ const lower = [
+ major,
+ minor,
+ patch
+ ];
+ let upper;
+ upper = major > 0 ? [
+ major + 1,
+ 0,
+ 0
+ ] : minor > 0 ? [
+ 0,
+ minor + 1,
+ 0
+ ] : [
+ 0,
+ 0,
+ patch + 1
+ ];
+ return {
+ lower,
+ upper
+ };
+}
+function computeWildcardBounds(value, parsingPolicy) {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
+ if (!cleanedText)
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ const parts = cleanedText.split(".");
+ const parseWildcardPart = (part) => {
+ if (parsingPolicy === "legacy-permissive") {
+ const parsed = parseInt(part, 10);
+ if (!isNaN(parsed))
+ return parsed;
+ } else
try {
- await this.response.body?.cancel();
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
} catch {}
- })();
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ };
+ const major = parseWildcardPart(parts[0]);
+ if (parts.length === 1)
+ return {
+ lower: [
+ major,
+ 0,
+ 0
+ ],
+ upper: [
+ major + 1,
+ 0,
+ 0
+ ]
+ };
+ const minor = parseWildcardPart(parts[1]);
+ return {
+ lower: [
+ major,
+ minor,
+ 0
+ ],
+ upper: [
+ major,
+ minor + 1,
+ 0
+ ]
+ };
+}
+function convertToDateTime(value) {
+ if (value instanceof Date)
+ return value;
+ if (typeof value == "string" || typeof value == "number") {
+ const date = new Date(value);
+ if (!isNaN(date.valueOf()))
+ return date;
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
}
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
}
-
-class PostHogFetchNetworkError extends Error {
- constructor(error) {
- super("Network error while fetching PostHog", error instanceof Error ? {
- cause: error
- } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+function relativeDateParseForFeatureFlagMatching(value) {
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
+ const match = value.match(regex);
+ const parsedDt = new Date(new Date().toISOString());
+ if (!match || !match.groups)
+ return null;
+ const number = parseInt(match.groups["number"]);
+ if (number >= 1e4)
+ return null;
+ const interval = match.groups["interval"];
+ if (interval === "h")
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
+ else if (interval === "d")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
+ else if (interval === "w")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
+ else if (interval === "m")
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
+ else {
+ if (interval !== "y")
+ return null;
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
}
+ return parsedDt;
}
-var applyCallerFeatureFlagOverrides = (target, callerProperties) => {
- for (const key of Object.keys(callerProperties))
- if (key.startsWith("$feature/") || key === "$active_feature_flags")
- target[key] = callerProperties[key];
-};
-async function logFlushError(err) {
- if (err instanceof PostHogFetchHttpError) {
- let text = "";
- try {
- text = await err.text;
- } catch {
- if (err.bodyReadTimedOut)
- text = "<response body read timed out>";
- }
- console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
+function matchFeatureFlagProperty(property, propertyValues, options = {}) {
+ const key = property.key;
+ const value = property.value;
+ const operator = property.operator || "exact";
+ const parsingPolicy = options.semverParsingPolicy ?? "strict";
+ const hasProperty = Object.prototype.hasOwnProperty.call(propertyValues, key);
+ if (hasProperty) {
+ if (operator === "is_not_set")
+ return false;
+ else if (operator === "is_set")
+ return true;
} else
- console.error("Error while flushing PostHog", err);
- return Promise.resolve();
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
+ const overrideValue = propertyValues[key];
+ if (overrideValue === undefined) {
+ options.warnFunction?.(`Property ${key} cannot have a value of undefined with the ${operator} operator`);
+ return operator === "is_not";
+ }
+ if (overrideValue === null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator) && operator !== "exact" && operator !== "is_not") {
+ options.warnFunction?.(`Property ${key} cannot have a value of null with the ${operator} operator`);
+ return false;
+ }
+ const computeExactMatch = (target, actual) => {
+ if (isTruthyOrFalsyPropertyValue(target)) {
+ assertJsonRepresentable(actual);
+ return isTruthyPropertyValue(target) === isTruthyPropertyValue(actual);
+ }
+ if (Array.isArray(target)) {
+ const actualString = exactMatchString(actual).toLowerCase();
+ return target.some((item) => exactMatchString(item).toLowerCase() === actualString);
+ }
+ return exactMatchString(target).toLowerCase() === exactMatchString(actual).toLowerCase();
+ };
+ const compare = (lhs, rhs, comparisonOperator) => {
+ if (comparisonOperator === "gt")
+ return lhs > rhs;
+ if (comparisonOperator === "gte")
+ return lhs >= rhs;
+ if (comparisonOperator === "lt")
+ return lhs < rhs;
+ if (comparisonOperator === "lte")
+ return lhs <= rhs;
+ throw new Error(`Invalid operator: ${comparisonOperator}`);
+ };
+ switch (operator) {
+ case "exact":
+ return computeExactMatch(value, overrideValue);
+ case "is_not":
+ return !computeExactMatch(value, overrideValue);
+ case "is_set":
+ return true;
+ case "icontains":
+ return asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "not_icontains":
+ return !asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "starts_with":
+ return asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "not_starts_with":
+ return !asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "ends_with":
+ return asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "not_ends_with":
+ return !asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
+ case "not_regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
+ case "gt":
+ case "gte":
+ case "lt":
+ case "lte": {
+ const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
+ const parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : 0 / 0;
+ if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
+ return compare(parsedOverride, parsedValue, operator);
+ return compare(String(overrideValue), String(value), operator);
+ }
+ case "is_date_after":
+ case "is_date_before": {
+ if (typeof value == "boolean")
+ throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
+ if (parsedDate == null)
+ parsedDate = convertToDateTime(value);
+ const overrideDate = convertToDateTime(overrideValue);
+ return operator === "is_date_before" ? overrideDate < parsedDate : overrideDate > parsedDate;
+ }
+ case "semver_eq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) === 0;
+ case "semver_neq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) !== 0;
+ case "semver_gt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) > 0;
+ case "semver_gte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) >= 0;
+ case "semver_lt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) < 0;
+ case "semver_lte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) <= 0;
+ case "semver_tilde": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeTildeBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_caret": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeCaretBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_wildcard": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeWildcardBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ default:
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
+ }
}
-function isPostHogFetchError(err) {
- return typeof err == "object" && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));
+async function hashSHA1(text) {
+ const subtle = globalThis.crypto?.subtle;
+ if (!subtle)
+ throw new Error("SubtleCrypto API not available");
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
+ return Array.from(new Uint8Array(hashBuffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
-function isPostHogFetchNetworkError(err) {
- return err instanceof PostHogFetchNetworkError;
+async function getFeatureFlagHash(key, bucketingValue, salt = "") {
+ const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
}
-function isRetryableFlagsFetchError(err) {
- if (err instanceof PostHogFetchHttpError)
- return err.status === 502 || err.status === 504;
- if (!(err instanceof PostHogFetchNetworkError))
- return false;
- const cause = err.error;
- const code = cause?.code ?? cause?.cause?.code;
- return code !== "ECONNREFUSED";
+function getFeatureFlagVariantLookupTable(variants) {
+ const table = [];
+ let valueMin = 0;
+ for (const variant of variants) {
+ const valueMax = valueMin + variant.rollout_percentage / 100;
+ table.push({
+ valueMin,
+ valueMax,
+ key: variant.key
+ });
+ valueMin = valueMax;
+ }
+ return table;
}
-function isPostHogFetchContentTooLargeError(err) {
- return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
+async function getFeatureFlagVariant(key, bucketingValue, variants) {
+ const hashValue = await getFeatureFlagHash(key, bucketingValue, "variant");
+ return getFeatureFlagVariantLookupTable(variants).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax)?.key;
}
-function isPostHogFetchRetryableError(err) {
- if (err instanceof PostHogFetchHttpError)
- return err.status === 408 || err.status === 429 || err.status >= 500;
- return isPostHogFetchNetworkError(err);
+function resolveFeatureFlagPayload(payloads, flagValue) {
+ if (flagValue === false || flagValue == null || !payloads)
+ return null;
+ const payloadKey = typeof flagValue == "boolean" ? flagValue.toString() : flagValue;
+ const payload = payloads[payloadKey] || null;
+ return payload == null ? null : parsePayload(payload);
}
-function isPostHogEventProperties(value) {
- return value !== null && typeof value == "object" && !Array.isArray(value);
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-any-value.mjs
+var INT64_RANGE_LIMIT = 9223372036854776000;
+var INT64_RANGE_LIMIT_DECIMAL = "9223372036854775808";
+var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
+function newState() {
+ return {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ };
}
-var DEFAULT_QUEUE_ROUTE = "default";
-
-class PostHogCoreStateless {
- getErrorPropertiesBuilder() {
- if (!this._errorPropertiesBuilder)
- this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();
- return this._errorPropertiesBuilder;
- }
- createErrorPropertiesBuilder() {
- return new ErrorPropertiesBuilder([
- new ErrorCoercer,
- new ObjectCoercer,
- new StringCoercer,
- new PrimitiveCoercer
- ], createDefaultStackParser());
+function toOtlpKeyValueList(attrs, logger) {
+ try {
+ return encodeKeyValueList(attrs, logger, newState(), 0);
+ } catch {
+ return [];
}
- constructor(apiKey, options = {}) {
- this.flushPromise = null;
- this.pendingFlushPromise = null;
- this.flushPromises = new Set;
- this._dequeuedMessagesCount = 0;
- this.shutdownPromise = null;
- this.promiseQueue = new PromiseQueue;
- this._events = new SimpleEventEmitter;
- this._isInitialized = false;
- const normalizedApiKey = typeof apiKey == "string" ? apiKey.trim() : "";
- const normalizedHost = typeof options.host == "string" ? options.host.trim() : "";
- const missingApiKey = !normalizedApiKey;
- this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
- if (missingApiKey)
- this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");
- this.apiKey = normalizedApiKey;
- this.host = removeTrailingSlash(normalizedHost || "https://us.i.posthog.com");
- this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
- this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
- this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);
- this.flushInterval = options.flushInterval ?? 1e4;
- this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
- this.defaultOptIn = options.defaultOptIn ?? true;
- this.disableSurveys = options.disableSurveys ?? false;
- this._retryOptions = {
- retryCount: options.fetchRetryCount ?? 3,
- retryDelay: options.fetchRetryDelay ?? 3000,
- retryCheck: isPostHogFetchRetryableError
+}
+function encodeBigInt(value, logger) {
+ const decimal = value.toString();
+ const limit = BigInt(INT64_RANGE_LIMIT_DECIMAL);
+ if (value >= limit || value < -limit) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
};
- this.requestTimeout = options.requestTimeout ?? 1e4;
- this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
- this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
- this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
- this.disableGeoip = options.disableGeoip ?? true;
- this.disabled = (options.disabled ?? false) || missingApiKey;
- this.historicalMigration = options?.historicalMigration ?? false;
- this._initPromise = Promise.resolve();
- this._isInitialized = true;
- this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
- if (options?.evaluationEnvironments && !options?.evaluationContexts)
- this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");
- this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
- }
- logMsgIfDebug(fn) {
- if (this.isDebug)
- fn();
}
- wrap(fn) {
- if (this.disabled)
- return void this._logger.warn("The client is disabled");
- if (this._isInitialized)
- return fn();
- this._initPromise.then(() => fn());
- }
- getCommonEventProperties() {
+ return {
+ intValue: decimal
+ };
+}
+function encodeAnyValue(value, logger, state, depth) {
+ if (state.remainingNodes <= 0)
return {
- $lib: this.getLibraryId(),
- $lib_version: this.getLibraryVersion()
+ stringValue: TRUNCATED_VALUE
};
- }
- get optedOut() {
- return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
- }
- async optIn() {
- this.wrap(() => {
- this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
- });
- }
- async optOut() {
- this.wrap(() => {
- this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
- });
- }
- on(event, cb) {
- return this._events.on(event, cb);
- }
- debug(enabled = true) {
- this.removeDebugCallback?.();
- if (enabled) {
- const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
- this.removeDebugCallback = () => {
- removeDebugCallback();
- this.removeDebugCallback = undefined;
+ state.remainingNodes--;
+ if (isBoolean(value))
+ return {
+ boolValue: value
+ };
+ if (typeof value == "bigint")
+ return encodeBigInt(value, logger);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ return {
+ stringValue: String(value)
+ };
+ if (Number.isInteger(value)) {
+ if (Number.isSafeInteger(value))
+ return {
+ intValue: String(value)
+ };
+ if ("u" < typeof BigInt)
+ return {
+ stringValue: String(value)
+ };
+ const decimal = BigInt(value).toString();
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
+ };
+ }
+ return {
+ intValue: decimal
};
}
+ return {
+ doubleValue: value
+ };
}
- get isDebug() {
- return !!this.removeDebugCallback;
- }
- get isDisabled() {
- return this.disabled;
- }
- buildPayload(payload) {
- const userProperties = payload.properties || {};
- let properties = {
- ...userProperties,
- ...this.getCommonEventProperties()
+ if (typeof value == "string")
+ return {
+ stringValue: sanitizeString(value)
};
- applyCallerFeatureFlagOverrides(properties, userProperties);
- if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
- properties = minimizeFlagCalledEventProperties(properties);
+ if (typeof value == "function")
return {
- distinct_id: payload.distinct_id,
- event: payload.event,
- properties
+ stringValue: FUNCTION_VALUE
};
- }
- isMinimalFlagCalledEventsEnabled() {
- return false;
- }
- addPendingPromise(promise) {
- return this.promiseQueue.add(promise);
- }
- identifyStateless(distinctId, properties, options) {
- this.wrap(() => {
- const payload = {
- ...this.buildPayload({
- distinct_id: distinctId,
- event: "$identify",
- properties
- })
- };
- this.enqueue("identify", payload, options);
- });
- }
- async identifyStatelessImmediate(distinctId, properties, options) {
- const payload = {
- ...this.buildPayload({
- distinct_id: distinctId,
- event: "$identify",
- properties
- })
+ if (typeof value == "symbol")
+ return {
+ stringValue: String(value)
};
- await this.sendImmediate("identify", payload, options);
+ if (typeof value == "object" && value !== null) {
+ if (state.ancestors.has(value))
+ return {
+ stringValue: CIRCULAR_VALUE
+ };
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return {
+ stringValue: TRUNCATED_VALUE
+ };
+ if (value instanceof Date) {
+ const time = value.getTime();
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
+ return {
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ };
+ }
+ state.ancestors.add(value);
+ try {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
+ return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
+ } catch {}
+ if (isArray(value))
+ return {
+ arrayValue: {
+ values: encodeArrayValues(value, logger, state, depth + 1)
+ }
+ };
+ return {
+ kvlistValue: {
+ values: encodeKeyValueList(value, logger, state, depth + 1)
+ }
+ };
+ } finally {
+ state.ancestors.delete(value);
+ }
}
- captureStateless(distinctId, event, properties, options) {
- this.wrap(() => {
- const payload = this.buildPayload({
- distinct_id: distinctId,
- event,
- properties
+ return {
+ stringValue: sanitizeString(String(value))
+ };
+}
+function encodeArrayValues(values, logger, state, depth) {
+ const result = [];
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ let index = 0;
+ for (;index < itemCount && state.remainingNodes > 0; index++)
+ try {
+ const element = index in values ? values[index] : undefined;
+ if (isNullish(element))
+ continue;
+ result.push(encodeAnyValue(element, logger, state, depth));
+ } catch {
+ result.push({
+ stringValue: UNSERIALIZABLE_VALUE
});
- this.enqueue("capture", payload, options);
+ }
+ if (values.length > index)
+ result.push({
+ stringValue: TRUNCATED_VALUE
});
+ return result;
+}
+function encodeKeyValueList(attrs, logger, state, depth) {
+ const result = [];
+ for (const key in attrs)
+ if (propertyIsEnumerable.call(attrs, key)) {
+ if (!key) {
+ logger?.debug("Dropping an attribute with an empty key");
+ continue;
+ }
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
+ logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
+ break;
+ }
+ try {
+ const value = attrs[key];
+ if (isNull(value) || isUndefined(value))
+ continue;
+ result.push({
+ key: sanitizeString(key),
+ value: encodeAnyValue(value, logger, state, depth)
+ });
+ } catch {
+ result.push({
+ key: sanitizeString(key),
+ value: {
+ stringValue: UNSERIALIZABLE_VALUE
+ }
+ });
+ }
+ }
+ return result;
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-resource.mjs
+function buildOtlpResourceAttributes(config, sdkName, sdkVersion) {
+ return {
+ ...assignUserAttributes({}, config.resourceAttributes),
+ "service.name": config.serviceName || "unknown_service",
+ ...config.environment && {
+ "deployment.environment": config.environment
+ },
+ ...config.serviceVersion && {
+ "service.version": config.serviceVersion
+ },
+ "telemetry.sdk.name": sdkName,
+ "telemetry.sdk.version": sdkVersion
+ };
+}
+var SDK_RESOURCE_KEYS = [
+ "service.name",
+ "deployment.environment",
+ "service.version",
+ "telemetry.sdk.name",
+ "telemetry.sdk.version"
+];
+function toOtlpResourceKeyValueList(attributes, logger) {
+ const user = assignUserAttributes({}, attributes);
+ const sdk = {};
+ for (const key of SDK_RESOURCE_KEYS)
+ if (Object.prototype.hasOwnProperty.call(user, key)) {
+ sdk[key] = user[key];
+ delete user[key];
+ }
+ return [
+ ...toOtlpKeyValueList(user, logger),
+ ...toOtlpKeyValueList(sdk, logger)
+ ];
+}
+var OS_NAMES = {
+ darwin: "macOS",
+ win32: "Windows",
+ cygwin: "Windows",
+ linux: "Linux",
+ android: "Android",
+ freebsd: "FreeBSD",
+ openbsd: "OpenBSD",
+ netbsd: "NetBSD",
+ sunos: "SunOS",
+ aix: "AIX",
+ haiku: "Haiku",
+ "Mac OS X": "macOS"
+};
+function normalizeOsName(name) {
+ if (!name)
+ return;
+ return Object.prototype.hasOwnProperty.call(OS_NAMES, name) ? OS_NAMES[name] : name;
+}
+function osResourceAttributes(name, version) {
+ const osName = normalizeOsName(name);
+ return {
+ ...osName ? {
+ "os.name": osName
+ } : {},
+ ...version ? {
+ "os.version": version
+ } : {}
+ };
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
+var OTLP_SEVERITY_MAP = {
+ trace: {
+ text: "TRACE",
+ number: 1
+ },
+ debug: {
+ text: "DEBUG",
+ number: 5
+ },
+ info: {
+ text: "INFO",
+ number: 9
+ },
+ warn: {
+ text: "WARN",
+ number: 13
+ },
+ error: {
+ text: "ERROR",
+ number: 17
+ },
+ fatal: {
+ text: "FATAL",
+ number: 21
}
- async captureStatelessImmediate(distinctId, event, properties, options) {
- const payload = this.buildPayload({
- distinct_id: distinctId,
- event,
- properties
- });
- await this.sendImmediate("capture", payload, options);
+};
+var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/flush-timer.mjs
+class FlushTimer {
+ constructor(_onFire) {
+ this._onFire = _onFire;
+ this._firesAt = 0;
+ }
+ get pending() {
+ return !!this._timer;
+ }
+ arm(delayMs) {
+ this.clear();
+ this._firesAt = Date.now() + delayMs;
+ this._timer = safeSetTimeout(() => {
+ this._timer = undefined;
+ this._onFire();
+ }, delayMs);
+ }
+ armNoEarlierThan(delayMs) {
+ if (this._timer && Date.now() + delayMs <= this._firesAt)
+ return;
+ this.arm(delayMs);
}
- aliasStateless(alias, distinctId, properties, options) {
- this.wrap(() => {
- const payload = this.buildPayload({
- event: "$create_alias",
- distinct_id: distinctId,
- properties: {
- ...properties || {},
- distinct_id: distinctId,
- alias
- }
- });
- this.enqueue("alias", payload, options);
- });
+ clear() {
+ if (this._timer) {
+ clearTimeout(this._timer);
+ this._timer = undefined;
+ }
}
- async aliasStatelessImmediate(alias, distinctId, properties, options) {
- const payload = this.buildPayload({
- event: "$create_alias",
- distinct_id: distinctId,
- properties: {
- ...properties || {},
- distinct_id: distinctId,
- alias
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/backoff.mjs
+var MAX_FLUSH_BACKOFF_EXPONENT = 6;
+var MAX_FLUSH_BACKOFF_MS = 30000;
+var JITTER = 0.25;
+function drawJitter() {
+ return 1 - JITTER + Math.random() * JITTER * 2;
+}
+var NO_JITTER = 1;
+function backoffDelayMs(baseMs, failures, jitter, maxMs) {
+ const exponent = Math.min(Math.max(0, failures - 1), MAX_FLUSH_BACKOFF_EXPONENT);
+ const delay = baseMs * 2 ** exponent;
+ const capped = maxMs === undefined ? delay : Math.min(delay, Math.max(maxMs, baseMs));
+ return Math.round(capped * jitter);
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
+var DEFAULT_HISTOGRAM_BOUNDS = [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 75,
+ 100,
+ 250,
+ 500,
+ 750,
+ 1000,
+ 2500,
+ 5000,
+ 7500,
+ 1e4
+];
+function msToUnixNano(ms) {
+ return String(ms) + "000000";
+}
+function seriesKey(type, name, unit, attributes) {
+ let attrsKey = "";
+ if (attributes) {
+ const keys = Object.keys(attributes).sort();
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
+ }
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
+}
+function bucketIndexFor(value, bounds) {
+ for (let i = 0;i < bounds.length; i++)
+ if (value <= bounds[i])
+ return i;
+ return bounds.length;
+}
+function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
+ return buildOtlpResourceAttributes(config, scopeName, scopeVersion);
+}
+function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
+ return {
+ resourceMetrics: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes)
+ },
+ scopeMetrics: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ metrics
+ }
+ ]
}
+ ]
+ };
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
+var DEFAULT_FLUSH_INTERVAL_MS = 1e4;
+var DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
+function resolveMetricsConfig(config) {
+ const resourceAttributes = config?.resourceAttributes;
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSend: config?.beforeSend,
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
+ };
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
+var OTLP_TEMPORALITY_DELTA = 1;
+
+class PostHogMetrics {
+ constructor(_instance, _config, _logger) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._series = new Map;
+ this._flushTimer = new FlushTimer(() => this.flush().catch((e) => {
+ this._logger.error("Metrics flush failed:", e);
+ }));
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ this._retryAfter = new RetryAfterWindow;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._generation = 0;
+ }
+ count(name, value = 1, options) {
+ this._capture({
+ name,
+ type: "count",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
});
- await this.sendImmediate("alias", payload, options);
}
- groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
- this.wrap(() => {
- const payload = this.buildPayload({
- distinct_id: distinctId || `$${groupType}_${groupKey}`,
- event: "$groupidentify",
- properties: {
- $group_type: groupType,
- $group_key: groupKey,
- $group_set: groupProperties || {},
- ...eventProperties || {}
- }
- });
- this.enqueue("capture", payload, options);
+ gauge(name, value, options) {
+ this._capture({
+ name,
+ type: "gauge",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
});
}
- async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
- const payload = this.buildPayload({
- distinct_id: distinctId || `$${groupType}_${groupKey}`,
- event: "$groupidentify",
- properties: {
- $group_type: groupType,
- $group_key: groupKey,
- $group_set: groupProperties || {},
- ...eventProperties || {}
- }
+ histogram(name, value, options) {
+ this._capture({
+ name,
+ type: "histogram",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
});
- await this.sendImmediate("capture", payload, options);
}
- async getRemoteConfig() {
- await this._initPromise;
- let host = this.host;
- if (host === "https://us.i.posthog.com")
- host = "https://us-assets.i.posthog.com";
- else if (host === "https://eu.i.posthog.com")
- host = "https://eu-assets.i.posthog.com";
- const url = `${host}/array/${this.apiKey}/config`;
- const fetchOptions = {
- method: "GET",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json"
- }
+ flush() {
+ const prev = this._flushPromise;
+ const run = async () => {
+ if (prev)
+ await prev.catch(() => {});
+ await this._doFlush();
};
- return this.fetchWithRetry(url, fetchOptions, {
- type: "required",
- consume: (response) => response.json()
- }, {
- retryCount: 0
- }, this.remoteConfigRequestTimeoutMs).catch((error) => {
- this._logger.error("Remote config could not be loaded", error);
- this._events.emit("error", error);
+ const p = run().finally(() => {
+ if (this._flushPromise === p)
+ this._flushPromise = null;
});
+ this._flushPromise = p;
+ return p;
}
- async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {
- await this._initPromise;
- const configParam = fetchConfig ? "&config=true" : "";
- const url = `${this.host}/flags/?v=2${configParam}`;
- const requestData = {
- token: this.apiKey,
- distinct_id: distinctId,
- groups,
- person_properties: personProperties,
- group_properties: groupProperties,
- ...extraPayload
- };
- if (personProperties.$device_id)
- requestData.$device_id = personProperties.$device_id;
- if (this.evaluationContexts && this.evaluationContexts.length > 0)
- requestData.evaluation_contexts = this.evaluationContexts;
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json"
- },
- body: JSON.stringify(requestData)
- };
- this._logger.info("Flags URL", url);
- return this.fetchWithRetry(url, fetchOptions, {
- type: "required",
- consume: (response) => response.json()
- }, {
- retryCount: this.featureFlagsRequestMaxRetries,
- retryCheck: isRetryableFlagsFetchError
- }, this.featureFlagsRequestTimeoutMs).then((response) => ({
- success: true,
- response: normalizeFlagsResponse(response)
- })).catch((error) => {
- this._events.emit("error", error);
- return {
- success: false,
- error: this.categorizeRequestError(error)
- };
- });
+ drainWindow() {
+ if (this._series.size === 0)
+ return null;
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ return this._buildPayload(window);
}
- categorizeRequestError(error) {
- if (error instanceof PostHogFetchHttpError)
- return {
- type: "api_error",
- statusCode: error.status
- };
- if (error instanceof PostHogFetchNetworkError) {
- const cause = error.error;
- if (cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError"))
- return {
- type: "timeout"
- };
- return {
- type: "connection_error"
+ reset() {
+ this._generation++;
+ this._retryAfter.reset();
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._flushTimer.clear();
+ this._series = new Map;
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ }
+ _capture(sample) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return;
+ const filtered = this._runBeforeSend(sample);
+ if (filtered === null)
+ return;
+ if (!filtered.name || typeof filtered.name != "string")
+ return void this._logger.warn("Dropping metric with empty name");
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
+ if (filtered.type === "count" && filtered.value < 0)
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
+ let attributes;
+ let key;
+ try {
+ attributes = filtered.attributes ? {
+ ...filtered.attributes
+ } : undefined;
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
+ } catch (e) {
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
+ return;
+ }
+ let state = this._series.get(key);
+ if (!state) {
+ if (!this._admitNewSeries())
+ return;
+ state = {
+ name: filtered.name,
+ type: filtered.type,
+ unit: filtered.unit,
+ attributes,
+ windowStartMs: Date.now()
};
+ this._series.set(key, state);
}
- return {
- type: "unknown_error"
- };
+ const seenType = this._typeByName.get(filtered.name);
+ if (seenType === undefined)
+ this._typeByName.set(filtered.name, filtered.type);
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
+ this._typeCollisionWarned.add(filtered.name);
+ this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
+ }
+ this._fold(state, filtered.value);
+ this._armFlushTimer();
}
- async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
- await this._initPromise;
- const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
- if (flagDetailResponse === undefined)
- return {
- response: undefined,
- requestId: undefined
- };
- let response = getFeatureFlagValue(flagDetailResponse.response);
- if (response === undefined)
- response = false;
- return {
- response,
- requestId: flagDetailResponse.requestId
- };
+ _admitNewSeries() {
+ if (this._series.size < this._config.maxSeriesPerFlush)
+ return true;
+ if (!this._seriesCapWarned) {
+ this._seriesCapWarned = true;
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
+ }
+ return false;
}
- async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
- await this._initPromise;
- const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
- key
- ]);
- if (flagsResponse === undefined)
- return;
- const featureFlags = flagsResponse.flags;
- const flagDetail = featureFlags[key];
- return {
- response: flagDetail,
- requestId: flagsResponse.requestId,
- evaluatedAt: flagsResponse.evaluatedAt
- };
+ _fold(state, value) {
+ switch (state.type) {
+ case "count":
+ state.total = (state.total ?? 0) + value;
+ break;
+ case "gauge":
+ state.last = value;
+ break;
+ case "histogram": {
+ if (!state.hist)
+ state.hist = {
+ count: 0,
+ sum: 0,
+ min: value,
+ max: value,
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
+ };
+ const hist = state.hist;
+ hist.count += 1;
+ hist.sum += value;
+ hist.min = Math.min(hist.min, value);
+ hist.max = Math.max(hist.max, value);
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
+ break;
+ }
+ }
+ }
+ _runBeforeSend(sample) {
+ const beforeSend = this._config.beforeSend;
+ if (!beforeSend)
+ return sample;
+ const fns = isArray(beforeSend) ? beforeSend : [
+ beforeSend
+ ];
+ let result = sample;
+ for (const fn of fns)
+ try {
+ const next = fn(result);
+ if (!next) {
+ this._logger.info("Metric was rejected in beforeSend function");
+ return null;
+ }
+ result = next;
+ } catch (e) {
+ this._logger.error("Error in beforeSend function for metric:", e);
+ return null;
+ }
+ return result;
}
- async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
- await this._initPromise;
- const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
- key
- ]);
- if (!payloads)
+ _armFlushTimer() {
+ if (this._flushTimer.pending)
return;
- const response = payloads[key];
- if (response === undefined)
- return null;
- return response;
- }
- async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
- return payloads;
- }
- async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
+ this._flushTimer.arm(this._nextFlushDelay());
}
- async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
- if (!featureFlagDetails)
- return {
- flags: undefined,
- payloads: undefined,
- requestId: undefined
- };
- return {
- flags: featureFlagDetails.featureFlags,
- payloads: featureFlagDetails.featureFlagPayloads,
- requestId: featureFlagDetails.requestId
- };
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
}
- async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
- await this._initPromise;
- const extraPayload = {
- geoip_disable: disableGeoip ?? this.disableGeoip
- };
- if (flagKeysToEvaluate)
- extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
- const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
- if (!result.success)
+ async _doFlush() {
+ this._flushTimer.clear();
+ if (this._series.size === 0)
return;
- const flagsResponse = result.response;
- if (flagsResponse.errorsWhileComputingFlags)
- console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");
- if (flagsResponse.quotaLimited?.includes("feature_flags")) {
- console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
- return {
- flags: {},
- featureFlags: {},
- featureFlagPayloads: {},
- requestId: flagsResponse?.requestId,
- quotaLimited: flagsResponse.quotaLimited
- };
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ const generation = this._generation;
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
+ if (generation !== this._generation)
+ return;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ } else {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ }
+ if (this._flushTimer.pending)
+ this._flushTimer.arm(this._nextFlushDelay());
+ switch (outcome.kind) {
+ case "ok":
+ return;
+ case "retry-later":
+ this._mergeWindowBack(window);
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ return;
+ case "too-large":
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
+ return;
+ case "fatal":
+ this._logger.error("Failed to send metrics batch:", outcome.error);
+ return;
}
- return flagsResponse;
}
- async getSurveysStateless() {
- await this._initPromise;
- if (this.disabled)
- return [];
- if (this.disableSurveys === true) {
- this._logger.info("Loading surveys is disabled.");
- return [];
+ _buildPayload(window) {
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
+ }
+ _buildMetrics(window) {
+ const nowNano = msToUnixNano(Date.now());
+ const byMetric = new Map;
+ for (const state of window.values()) {
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
+ let metric = byMetric.get(metricKey);
+ if (!metric) {
+ metric = {
+ name: state.name,
+ ...state.unit && {
+ unit: state.unit
+ }
+ };
+ if (state.type === "count")
+ metric.sum = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ isMonotonic: true,
+ dataPoints: []
+ };
+ else if (state.type === "gauge")
+ metric.gauge = {
+ dataPoints: []
+ };
+ else
+ metric.histogram = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ dataPoints: []
+ };
+ byMetric.set(metricKey, metric);
+ }
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
+ const startNano = msToUnixNano(state.windowStartMs);
+ if (state.type === "count") {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ asDouble: state.total ?? 0
+ };
+ metric.sum.dataPoints.push(dp);
+ } else if (state.type === "gauge") {
+ const dp = {
+ attributes,
+ timeUnixNano: nowNano,
+ asDouble: state.last ?? 0
+ };
+ metric.gauge.dataPoints.push(dp);
+ } else if (state.hist) {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ count: state.hist.count,
+ sum: state.hist.sum,
+ min: state.hist.min,
+ max: state.hist.max,
+ bucketCounts: state.hist.bucketCounts,
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
+ };
+ metric.histogram.dataPoints.push(dp);
+ }
}
- const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
- const fetchOptions = {
- method: "GET",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json"
+ return Array.from(byMetric.values());
+ }
+ _mergeWindowBack(window) {
+ for (const [key, old] of window) {
+ const current = this._series.get(key);
+ if (!current) {
+ if (this._admitNewSeries())
+ this._series.set(key, old);
+ continue;
}
- };
- const response = await this.fetchWithRetry(url, fetchOptions, {
- type: "required",
- consume: (response) => {
- if (response.status !== 200 || !response.json) {
- const msg = `Surveys API could not be loaded: ${response.status}`;
- const error = new Error(msg);
- this._logger.error(error);
- this._events.emit("error", new Error(msg));
- return Promise.resolve(undefined);
- }
- return response.json();
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
+ switch (current.type) {
+ case "count":
+ current.total = (current.total ?? 0) + (old.total ?? 0);
+ break;
+ case "gauge":
+ break;
+ case "histogram":
+ if (old.hist)
+ if (current.hist) {
+ current.hist.count += old.hist.count;
+ current.hist.sum += old.hist.sum;
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
+ } else
+ current.hist = old.hist;
+ break;
}
- }).catch((error) => {
- this._logger.error("Surveys API could not be loaded", error);
- this._events.emit("error", error);
- });
- const newSurveys = response?.surveys;
- if (newSurveys)
- this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
- return newSurveys ?? [];
+ }
}
- get props() {
- if (!this._props)
- this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
- return this._props || {};
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/ids.mjs
+var TRACE_ID_BYTES = 16;
+var SPAN_ID_BYTES = 8;
+var TRACE_ID_HEX = 2 * TRACE_ID_BYTES;
+var SPAN_ID_HEX = 2 * SPAN_ID_BYTES;
+var INVALID_TRACE_ID = "0".repeat(TRACE_ID_HEX);
+var INVALID_SPAN_ID = "0".repeat(SPAN_ID_HEX);
+var HEX_RE = /^[0-9a-f]+$/;
+function getRandomBytes(byteLength) {
+ const bytes = new Uint8Array(byteLength);
+ const cryptoLike = globalThis.crypto;
+ if (cryptoLike && typeof cryptoLike.getRandomValues == "function")
+ try {
+ cryptoLike.getRandomValues(bytes);
+ return bytes;
+ } catch {}
+ for (let i = 0;i < byteLength; i++)
+ bytes[i] = Math.floor(256 * Math.random());
+ return bytes;
+}
+function bytesToHex(bytes) {
+ let hex = "";
+ for (let i = 0;i < bytes.length; i++)
+ hex += bytes[i].toString(16).padStart(2, "0");
+ return hex;
+}
+function randomHexId(byteLength) {
+ const hex = bytesToHex(getRandomBytes(byteLength));
+ return /[^0]/.test(hex) ? hex : hex.slice(0, -1) + "1";
+}
+function newTraceId() {
+ return randomHexId(TRACE_ID_BYTES);
+}
+function newSpanId() {
+ return randomHexId(SPAN_ID_BYTES);
+}
+function isValidHexId(value, length, invalid) {
+ return typeof value == "string" && value.length === length && value !== invalid && HEX_RE.test(value);
+}
+function isValidTraceId(value) {
+ return isValidHexId(value, TRACE_ID_HEX, INVALID_TRACE_ID);
+}
+function isValidSpanId(value) {
+ return isValidHexId(value, SPAN_ID_HEX, INVALID_SPAN_ID);
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/traceparent.mjs
+var TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
+function parseTraceparent(value) {
+ const fields = matchTraceparent(value);
+ return fields && {
+ traceId: fields.traceId,
+ spanId: fields.spanId,
+ flags: definedFlags(fields.flags)
+ };
+}
+function definedFlags(flags) {
+ return 1 & parseInt(flags, 16) ? TRACE_FLAGS_SAMPLED : TRACE_FLAGS_UNSAMPLED;
+}
+function matchTraceparent(value) {
+ if (typeof value != "string")
+ return;
+ const match = TRACEPARENT_RE.exec(value.trim());
+ if (!match)
+ return;
+ const [, version, traceId, spanId, flags, trailing] = match;
+ if (version === "ff")
+ return;
+ if (version === "00" && trailing)
+ return;
+ if (!isValidTraceId(traceId) || !isValidSpanId(spanId))
+ return;
+ return {
+ version,
+ traceId,
+ spanId,
+ flags
+ };
+}
+function normalizeTraceparent(value) {
+ return matchTraceparent(value) && value.trim();
+}
+function traceparentHeader(value) {
+ return Array.isArray(value) && value.length === 1 ? value[0] : value;
+}
+var TRACE_FLAGS_SAMPLED = "01";
+var TRACE_FLAGS_UNSAMPLED = "00";
+function formatTraceparent(traceId, spanId, flags = TRACE_FLAGS_SAMPLED) {
+ return `00-${traceId}-${spanId}-${flags}`;
+}
+var TRACESTATE_MAX_MEMBERS = 32;
+var TRACESTATE_MAX_LENGTH = 512;
+function sanitizeTracestate(value) {
+ if (typeof value != "string")
+ return;
+ const trimmed = value.trim();
+ if (!trimmed)
+ return;
+ if (/[^\x20-\x7e\t]/.test(trimmed))
+ return;
+ const members = trimmed.split(",");
+ if (members.length > TRACESTATE_MAX_MEMBERS)
+ return;
+ for (const member of members)
+ if (member.trim() && !member.includes("="))
+ return;
+ if (trimmed.length <= TRACESTATE_MAX_LENGTH)
+ return trimmed;
+ return trimToLength(members);
+}
+var TRACESTATE_LARGE_MEMBER_LENGTH = 128;
+function trimToLength(members) {
+ const kept = [
+ ...members
+ ];
+ const joinedLength = () => kept.reduce((total, member) => total + member.length, 0) + kept.length - 1;
+ for (let index = kept.length - 1;index >= 0 && joinedLength() > TRACESTATE_MAX_LENGTH; index--)
+ if (kept[index].length > TRACESTATE_LARGE_MEMBER_LENGTH)
+ kept.splice(index, 1);
+ while (kept.length && joinedLength() > TRACESTATE_MAX_LENGTH)
+ kept.pop();
+ return kept.length ? kept.join(",") : undefined;
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/sanitize.mjs
+var FALLBACK_SPAN_NAME = "unknown";
+var MAX_TIMESTAMP_MS = 9223372036854;
+var MIN_TIMESTAMP_MS = 0;
+var DEEP_BACKDATE_WARNING_MS = 86400000;
+function sanitizeName(name, label, maxLength, logger) {
+ if (typeof name == "string" && name.trim())
+ return name.length > maxLength ? name.slice(0, maxLength) : name;
+ logger?.debug(`${label} must be a non-empty string; using "${FALLBACK_SPAN_NAME}"`);
+ return FALLBACK_SPAN_NAME;
+}
+function toEpochMs(value) {
+ if (value == null)
+ return;
+ let ms = value;
+ if (value instanceof Date)
+ try {
+ ms = value.getTime();
+ } catch {
+ return;
+ }
+ if (typeof ms != "number" || !Number.isFinite(ms))
+ return;
+ if (ms < MIN_TIMESTAMP_MS || ms > MAX_TIMESTAMP_MS)
+ return;
+ return ms;
+}
+function resolveStartTime(value, now, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug("Span startTime is out of range or not a valid time; using the current time");
+ return now;
}
- set props(val) {
- this._props = val;
+ if (now - supplied > DEEP_BACKDATE_WARNING_MS)
+ logger?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp");
+ else if (supplied > now)
+ logger?.debug("Span startTime is in the future; the span may export with a zero duration");
+ return supplied;
+}
+function clampEndTime(endTime, startTime) {
+ return endTime < startTime ? startTime : endTime;
+}
+function resolveSuppliedTime(value, derived, label, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug(`Span ${label} is out of range or not a valid time; using the derived time`);
+ return derived;
}
- async register(properties) {
- this.wrap(() => {
- this.props = {
- ...this.props,
- ...properties
+ return supplied;
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/span.mjs
+function monotonicNow() {
+ const perf = globalThis.performance;
+ return typeof perf?.now == "function" ? perf.now() : undefined;
+}
+
+class PostHogSpan {
+ constructor(init, _onEnd, _logger) {
+ this._onEnd = _onEnd;
+ this._logger = _logger;
+ this._events = [];
+ this._ended = false;
+ this._userAttributeCount = 0;
+ this._userEventCount = 0;
+ this._droppedAttributes = 0;
+ this._droppedEvents = 0;
+ this._traceId = init.traceId;
+ this._spanId = init.spanId;
+ this._parentSpanId = init.parentSpanId;
+ this._traceState = init.traceState;
+ this._traceFlags = init.traceFlags ?? TRACE_FLAGS_SAMPLED;
+ this._parentIsRemote = init.parentIsRemote ?? false;
+ this._name = init.name;
+ this._kind = init.kind;
+ this._autoKeys = new Set(init.autoAttributeKeys);
+ this._maxAttributes = init.maxAttributes;
+ this._maxEvents = init.maxEvents;
+ this._maxAttributesPerEvent = init.maxAttributesPerEvent;
+ this._maxAttributeValueLength = init.maxAttributeValueLength;
+ this._attributes = Object.create(null);
+ for (const key of Object.keys(init.attributes))
+ this._writeAttribute(key, init.attributes[key]);
+ this._startMono = init.backdated ? undefined : monotonicNow();
+ this._startTime = init.clockAnchor && this._startMono !== undefined ? init.clockAnchor.wall + (this._startMono - init.clockAnchor.mono) : init.startTime;
+ if (this._startMono !== undefined)
+ this._clockAnchor = init.clockAnchor ?? {
+ wall: this._startTime,
+ mono: this._startMono
};
- this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
- });
- }
- async unregister(property) {
- this.wrap(() => {
- delete this.props[property];
- this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
- });
}
- processBeforeEnqueue(message) {
- return message;
+ _now() {
+ if (this._startMono !== undefined) {
+ const mono = monotonicNow();
+ if (mono !== undefined)
+ return this._startTime + Math.max(0, mono - this._startMono);
+ }
+ return Date.now();
}
- async flushStorage() {}
- getQueueRouteKey(_message) {
- return DEFAULT_QUEUE_ROUTE;
+ _mutable(operation) {
+ if (this._ended) {
+ this._logger?.debug(`Ignoring ${operation} on a span that has already ended`);
+ return false;
+ }
+ return true;
}
- persistedQueueKeyForRoute(_route) {
- return types_PostHogPersistedProperty.Queue;
+ _writeAttribute(key, value) {
+ if (isNullish(value)) {
+ if (key in this._attributes && !this._autoKeys.has(key))
+ this._userAttributeCount--;
+ delete this._attributes[key];
+ return;
+ }
+ if (!this._autoKeys.has(key) && !(key in this._attributes)) {
+ if (this._userAttributeCount >= this._maxAttributes)
+ return void this._droppedAttributes++;
+ this._userAttributeCount++;
+ }
+ this._attributes[key] = truncateAttributeValue(value, this._maxAttributeValueLength);
}
- getActiveQueueRoutes() {
- return [
- DEFAULT_QUEUE_ROUTE
- ];
+ setAttribute(key, value) {
+ if (this._mutable("setAttribute"))
+ this._writeAttribute(key, value);
+ return this;
}
- getRouteQueue(route) {
- return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
+ setAttributes(attributes) {
+ if (this._mutable("setAttributes")) {
+ const safe = assignUserAttributes({}, attributes);
+ for (const key of Object.keys(safe))
+ this._writeAttribute(key, safe[key]);
+ }
+ return this;
}
- enqueue(type, _message, options, explicitRoute) {
- this.wrap(() => {
- if (this.optedOut)
- return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
- let message = this.prepareMessage(_message, options);
- message = this.processBeforeEnqueue(message);
- if (message === null)
- return;
- message = this.normalizeMessage(message);
- const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
- const queue = this.getPersistedProperty(queueKey) || [];
- if (queue.length >= this.maxQueueSize) {
- queue.shift();
- this._logger.warn("Queue is full, the oldest event is dropped.");
+ addEvent(name, attributes, timestamp) {
+ if (this._mutable("addEvent")) {
+ if (this._userEventCount >= this._maxEvents) {
+ this._droppedEvents++;
+ return this;
}
- queue.push({
- message
+ this._userEventCount++;
+ const bounded = attributes && boundAttributes(attributes, this._maxAttributesPerEvent, this._maxAttributeValueLength);
+ this._events.push({
+ name: sanitizeName(name, "Span event name", this._maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(timestamp, this._now(), "event timestamp", this._logger),
+ ...bounded && {
+ attributes: bounded.attributes,
+ ...bounded.dropped && {
+ droppedAttributesCount: bounded.dropped
+ }
+ }
});
- this.setPersistedProperty(queueKey, queue);
- this._events.emit(type, message);
- if (queue.length >= this.flushAt)
- this.flushBackground();
- if (this.flushInterval && !this._flushTimer)
- this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
- });
- }
- async sendImmediate(type, _message, options, explicitRoute) {
- if (this.disabled)
- return void this._logger.warn("The client is disabled");
- if (!this._isInitialized)
- await this._initPromise;
- if (this.optedOut)
- return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
- let message = this.prepareMessage(_message, options);
- message = this.processBeforeEnqueue(message);
- if (message === null)
- return;
- message = this.normalizeMessage(message);
- try {
- await this.sendBatch([
- message
- ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
- } catch (err) {
- this._events.emit("error", err);
}
+ return this;
}
- normalizeMessage(message) {
- const { type: _type, library, library_version, ...sanitizedMessage } = message;
- let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
- if (library !== undefined && properties?.$lib === undefined)
- properties = {
- ...properties || {},
- $lib: library
- };
- if (library_version !== undefined && properties?.$lib_version === undefined)
- properties = {
- ...properties || {},
- $lib_version: library_version
+ setStatus(status, message) {
+ if (this._mutable("setStatus")) {
+ if (status !== "ok" && status !== "error") {
+ this._logger?.debug(`Ignoring unknown span status "${String(status)}"; expected "ok" or "error"`);
+ return this;
+ }
+ this._status = {
+ code: status,
+ ...message && {
+ message: truncateString(message, this._maxAttributeValueLength)
+ }
};
- if (properties)
- sanitizedMessage.properties = properties;
- sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
- return sanitizedMessage;
- }
- normalizeTimestampForWire(timestamp) {
- const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
- if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
- return timestamp;
- const normalized = parsedTimestamp.toISOString();
- const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
- return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
- }
- prepareMessage(_message, options) {
- const message = {
- ..._message,
- timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
- uuid: getEventUuid(options?.uuid, uuidv7)
- };
- const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
- if (addGeoipDisableProperty) {
- if (!isPostHogEventProperties(message.properties))
- message.properties = {};
- message.properties["$geoip_disable"] = true;
- }
- if (message.distinctId) {
- message.distinct_id = message.distinctId;
- delete message.distinctId;
}
- return message;
+ return this;
}
- clearFlushTimer() {
- if (this._flushTimer) {
- clearTimeout(this._flushTimer);
- this._flushTimer = undefined;
- }
+ get statusIsExplicitlyOk() {
+ return this._status?.code === "ok";
}
- flushBackground() {
- if (this.pendingFlushPromise)
- return;
- this.flush().catch(async (err) => {
- await logFlushError(err);
+ recordException(error) {
+ if (!this._mutable("recordException"))
+ return this;
+ const { type, message, stack } = describeError(error);
+ this.addEvent(EXCEPTION_EVENT_NAME, {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
+ }
});
+ return this.setStatus("error", message);
}
- async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
- const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
- let iteration = 0;
- while (true) {
- const promises = this.promiseQueue.getPromises([
- ...ignoredPendingPromises,
- ...this.flushPromises
- ], maxPromiseId);
- if (promises.length === 0)
- return;
- if (iteration > 0)
- this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
- await Promise.all(promises.map((promise) => promise.catch(() => {})));
- iteration++;
- }
- }
- flushWithPendingPromises() {
- return this.flushInternal(true);
+ updateName(name) {
+ if (this._mutable("updateName"))
+ this._name = sanitizeName(name, "Span name", this._maxAttributeValueLength, this._logger);
+ return this;
}
- flush() {
- return this.flushInternal(false);
+ traceparent() {
+ return formatTraceparent(this._traceId, this._spanId, this._traceFlags);
}
- flushInternal(waitForPendingPromises) {
- if (this.disabled)
- return Promise.resolve();
- if (!waitForPendingPromises && this.pendingFlushPromise)
- return this.pendingFlushPromise;
- const previousFlushPromise = this.flushPromise;
- const maxPromiseId = this.promiseQueue.maxId;
- const nextFlushPromise = Promise.resolve().then(() => {
- if (waitForPendingPromises)
- return this.waitForPendingPromises(maxPromiseId, [
- previousFlushPromise,
- nextFlushPromise
- ]);
- }).then(() => allSettled([
- previousFlushPromise
- ])).then(() => {
- if (this.pendingFlushPromise === nextFlushPromise)
- this.pendingFlushPromise = null;
- return this._flush();
- });
- this.pendingFlushPromise = nextFlushPromise;
- this.flushPromise = nextFlushPromise;
- this.flushPromises.add(nextFlushPromise);
- this.addPendingPromise(nextFlushPromise);
- allSettled([
- nextFlushPromise
- ]).then(() => {
- this.flushPromises.delete(nextFlushPromise);
- if (this.pendingFlushPromise === nextFlushPromise)
- this.pendingFlushPromise = null;
- if (this.flushPromise === nextFlushPromise)
- this.flushPromise = null;
- });
- return nextFlushPromise;
+ tracestate() {
+ return this._traceState ?? null;
}
- getCustomHeaders() {
- const customUserAgent = this.getCustomUserAgent();
- const headers = {};
- if (customUserAgent && customUserAgent !== "")
- headers["User-Agent"] = customUserAgent;
- return headers;
+ childContext() {
+ return {
+ traceId: this._traceId,
+ parentSpanId: this._spanId,
+ traceState: this._traceState,
+ traceFlags: this._traceFlags,
+ clockAnchor: this._clockAnchor
+ };
}
- compressPayload(payload) {
- return gzipCompress(payload, this.isDebug);
+ end(endTime) {
+ if (this._ended)
+ return void this._logger?.debug("Ignoring end() on a span that has already ended");
+ this._ended = true;
+ const derived = this._now();
+ const resolved = resolveSuppliedTime(endTime, derived, "end time", this._logger);
+ this._onEnd({
+ traceId: this._traceId,
+ spanId: this._spanId,
+ ...this._parentSpanId && {
+ parentSpanId: this._parentSpanId
+ },
+ ...this._traceState && {
+ traceState: this._traceState
+ },
+ traceFlags: this._traceFlags,
+ parentIsRemote: this._parentIsRemote,
+ name: this._name,
+ kind: this._kind,
+ ...this._status && {
+ status: this._status
+ },
+ attributes: {
+ ...this._attributes
+ },
+ events: this._events,
+ startTime: this._startTime,
+ endTime: clampEndTime(resolved, this._startTime),
+ ...this._droppedAttributes && {
+ droppedAttributesCount: this._droppedAttributes
+ },
+ ...this._droppedEvents && {
+ droppedEventsCount: this._droppedEvents
+ }
+ }, this._autoKeys);
}
- getBatchEndpointPath(_route) {
- return "/batch/";
+}
+var EXCEPTION_EVENT_NAME = "exception";
+var MAX_UINT32 = 4294967295;
+function safeString(value) {
+ try {
+ return typeof value == "string" ? value : String(value);
+ } catch {
+ return UNSERIALIZABLE_VALUE;
}
- async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
- const data = {
- api_key: this.apiKey,
- batch: batchMessages.map((message) => {
- if (!message)
- return message;
- const timestamp = this.normalizeTimestampForWire(message.timestamp);
- return timestamp === message.timestamp ? message : {
- ...message,
- timestamp
- };
- }),
- sent_at: currentISOTime()
- };
- if (this.historicalMigration)
- data.historical_migration = true;
- const payload = safeJsonStringify(data);
- const url = `${this.host}${this.getBatchEndpointPath(route)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
+}
+function nonNegativeCount(value) {
+ if (typeof value != "number" || !Number.isFinite(value) || value <= 0)
+ return 0;
+ return Math.min(Math.floor(value), MAX_UINT32);
+}
+function orderedKeys(attributes, keysBeforeHook) {
+ if (!keysBeforeHook.length)
+ return Object.keys(attributes);
+ const beforeHook = keysBeforeHook.filter((key) => Object.prototype.propertyIsEnumerable.call(attributes, key));
+ const seen = new Set(beforeHook);
+ return [
+ ...beforeHook,
+ ...Object.keys(attributes).filter((key) => !seen.has(key))
+ ];
+}
+function applySpanLimits(record, autoKeys, maxAttributes, maxEvents, maxAttributesPerEvent, maxAttributeValueLength, keysBeforeHook = []) {
+ let kept = 0;
+ let droppedAttributes = 0;
+ const attributes = {};
+ for (const key of orderedKeys(record.attributes, keysBeforeHook)) {
+ const value = record.attributes[key];
+ if (!isNullish(value)) {
+ if (!autoKeys.has(key)) {
+ if (kept >= maxAttributes) {
+ droppedAttributes++;
+ continue;
}
- },
- body: gzippedPayload || payload
+ kept++;
+ }
+ Object.defineProperty(attributes, key, {
+ value: truncateAttributeValue(value, maxAttributeValueLength),
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ }
+ record.attributes = attributes;
+ if (droppedAttributes)
+ record.droppedAttributesCount = nonNegativeCount(record.droppedAttributesCount) + droppedAttributes;
+ let keptEvents = 0;
+ let droppedEvents = 0;
+ const events = [];
+ for (const event of record.events) {
+ if (keptEvents >= maxEvents) {
+ droppedEvents++;
+ continue;
+ }
+ keptEvents++;
+ if (event.attributes) {
+ const bounded = boundAttributes(event.attributes, maxAttributesPerEvent, maxAttributeValueLength);
+ event.attributes = bounded.attributes;
+ if (bounded.dropped)
+ event.droppedAttributesCount = nonNegativeCount(event.droppedAttributesCount) + bounded.dropped;
+ }
+ events.push(event);
+ }
+ record.events = events;
+ if (droppedEvents)
+ record.droppedEventsCount = nonNegativeCount(record.droppedEventsCount) + droppedEvents;
+ if (record.status?.message)
+ record.status = {
+ ...record.status,
+ message: truncateString(safeString(record.status.message), maxAttributeValueLength)
};
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, retryOptions);
+}
+
+class NoopSpan {
+ setAttribute() {
+ return this;
}
- async _flush() {
- this.clearFlushTimer();
- await this._initPromise;
- const routes = this.getActiveQueueRoutes();
- if (!routes.some((route) => this.getRouteQueue(route).length > 0))
- return;
- const sentMessages = [];
- let firstError;
- for (const route of routes)
- try {
- await this._flushRoute(route, sentMessages);
- } catch (err) {
- if (firstError === undefined)
- firstError = err;
- }
- if (firstError !== undefined)
- throw firstError;
- this._events.emit("flush", sentMessages);
+ setAttributes() {
+ return this;
}
- async _flushRoute(route, sentMessages) {
- const queueKey = this.persistedQueueKeyForRoute(route);
- let queue = this.getPersistedProperty(queueKey) || [];
- if (!queue.length)
- return;
- const originalQueueLength = queue.length;
- let sentFromRoute = 0;
- while (queue.length > 0 && sentFromRoute < originalQueueLength) {
- const batchItems = queue.slice(0, this.maxBatchSize);
- const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
- const persistQueueChange = async () => {
- const refreshedQueue = this.getPersistedProperty(queueKey) || [];
- const remainingBatchItems = [
- ...batchItems
- ];
- const newQueue = refreshedQueue.filter((item) => {
- const itemUuid = item.message?.uuid;
- const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
- if (batchItemIndex === -1)
- return true;
- remainingBatchItems.splice(batchItemIndex, 1);
- return false;
- });
- this.setPersistedProperty(queueKey, newQueue);
- queue = newQueue;
- this._dequeuedMessagesCount += batchItems.length;
- await this.flushStorage();
- };
- const retryOptions = {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
+ addEvent() {
+ return this;
+ }
+ setStatus() {
+ return this;
+ }
+ recordException() {
+ return this;
+ }
+ updateName() {
+ return this;
+ }
+ traceparent() {
+ return null;
+ }
+ tracestate() {
+ return null;
+ }
+ end() {}
+}
+var NOOP_SPAN = /* @__PURE__ */ new NoopSpan;
+
+class PassThroughSpan extends NoopSpan {
+ constructor(_traceparent, _tracestate) {
+ super(), this._traceparent = _traceparent, this._tracestate = _tracestate;
+ }
+ traceparent() {
+ return this._traceparent;
+ }
+ tracestate() {
+ return this._tracestate ?? null;
+ }
+}
+function readStack(error) {
+ try {
+ const stack = error.stack;
+ return typeof stack == "string" && stack ? {
+ stack
+ } : {};
+ } catch {
+ return {};
+ }
+}
+function inertSpan(options, active) {
+ const parent = traceparentHeader(options?.parent) ?? active;
+ const inbound = typeof parent == "string" || parent == null ? parent : readHandle(parent, "traceparent");
+ const traceparent = normalizeTraceparent(inbound);
+ if (!traceparent)
+ return NOOP_SPAN;
+ const tracestate = typeof parent == "string" || parent == null ? options?.tracestate : readHandle(parent, "tracestate");
+ return new PassThroughSpan(traceparent, sanitizeTracestate(tracestate));
+}
+function readHandle(parent, method) {
+ try {
+ const fn = parent[method];
+ return typeof fn == "function" ? fn.call(parent) : undefined;
+ } catch {
+ return;
+ }
+}
+function truncateString(value, maxLength) {
+ return value.length > maxLength ? value.slice(0, maxLength) : value;
+}
+function truncateAttributeValue(value, maxLength) {
+ return truncateValue(value, maxLength, {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ }, 0);
+}
+function truncateValue(value, maxLength, state, depth) {
+ if (value === null || typeof value != "object") {
+ if (isNullish(value))
+ return value;
+ if (state.remainingNodes <= 0)
+ return value;
+ state.remainingNodes--;
+ return typeof value == "string" ? truncateString(value, maxLength) : value;
+ }
+ if (state.ancestors.has(value))
+ return CIRCULAR_VALUE;
+ if (state.remainingNodes <= 0 || depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return value;
+ state.remainingNodes--;
+ state.ancestors.add(value);
+ try {
+ if (value instanceof Date)
+ return value;
+ const resolved = resolveToJson(value);
+ if (resolved.selfDescribed)
+ return isNullish(resolved.value) ? String(resolved.value) : truncateValue(resolved.value, maxLength, state, depth + 1);
+ if (isArray(value)) {
+ const walked = Math.min(value.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ const boundedItems = [];
+ for (let index = 0;index < walked; index++)
+ try {
+ boundedItems.push(truncateValue(value[index], maxLength, state, depth + 1));
+ } catch {
+ boundedItems.push(UNSERIALIZABLE_VALUE);
}
- };
+ if (value.length > walked)
+ boundedItems.length = value.length;
+ return boundedItems;
+ }
+ const bounded = {};
+ let emittable = 0;
+ for (const key of Object.keys(value)) {
+ if (emittable >= MAX_JSON_SAFE_VALUE_ITEMS)
+ break;
+ let boundedItem;
try {
- await this.sendBatch(batchMessages, retryOptions, route);
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
- this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
- this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
- continue;
- }
- if (!(err instanceof PostHogFetchNetworkError))
- await persistQueueChange();
- this._events.emit("error", err);
- throw err;
+ boundedItem = truncateValue(value[key], maxLength, state, depth + 1);
+ } catch {
+ boundedItem = UNSERIALIZABLE_VALUE;
}
- await persistQueueChange();
- sentMessages.push(...batchMessages);
- sentFromRoute += batchMessages.length;
+ if (key && !isNullish(boundedItem))
+ emittable++;
+ Object.defineProperty(bounded, key, {
+ value: boundedItem,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
}
+ return bounded;
+ } catch {
+ return value;
+ } finally {
+ state.ancestors.delete(value);
}
- async _sendLogsBatch(payload) {
- if (this.disabled)
+}
+function resolveToJson(value) {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
return {
- kind: "fatal",
- error: new Error("The client is disabled")
+ selfDescribed: true,
+ value: toJSON.call(value)
};
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
+ } catch {}
+ return {
+ selfDescribed: false
+ };
+}
+function boundAttributes(source, max, maxLength) {
+ let keys;
+ try {
+ keys = Object.keys(source);
+ } catch {
+ return {
+ attributes: {},
+ dropped: 0
};
+ }
+ const attributes = {};
+ let kept = 0;
+ let dropped = 0;
+ for (const key of keys) {
+ if (kept >= max) {
+ dropped++;
+ continue;
+ }
+ let value;
try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
- }
+ value = truncateAttributeValue(source[key], maxLength);
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ if (!isNullish(value)) {
+ kept++;
+ Object.defineProperty(attributes, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
});
+ }
+ }
+ return {
+ attributes,
+ dropped
+ };
+}
+function truncateAttributes(attributes, maxLength) {
+ for (const key of Object.keys(attributes))
+ attributes[key] = truncateAttributeValue(attributes[key], maxLength);
+ return attributes;
+}
+function runWithActiveSpan(contextManager, span, fn) {
+ return span === NOOP_SPAN ? fn(span) : contextManager.with(span, () => fn(span));
+}
+function describeError(error) {
+ try {
+ const stack = readStack(error);
+ if (isError(error))
return {
- kind: "ok"
+ type: error.name || "Error",
+ message: error.message || "",
+ ...stack
};
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (err instanceof PostHogFetchNetworkError)
+ if (typeof error == "string")
+ return {
+ type: "string",
+ message: error
+ };
+ if (error && typeof error == "object") {
+ const maybe = error;
+ if (typeof maybe.message == "string")
return {
- kind: "retry-later",
- error: err
+ type: typeof maybe.name == "string" ? maybe.name : "Object",
+ message: maybe.message,
+ ...stack
};
- return {
- kind: "fatal",
- error: err
+ }
+ return {
+ type: typeof error,
+ message: String(error)
+ };
+ } catch {
+ return {
+ type: typeof error,
+ message: ""
+ };
+ }
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/otlp.mjs
+var SPAN_KIND_TO_OTLP = {
+ internal: 1,
+ server: 2,
+ client: 3,
+ producer: 4,
+ consumer: 5
+};
+var SPAN_STATUS_TO_OTLP = {
+ ok: 1,
+ error: 2
+};
+var TRACE_FLAGS_SAMPLED2 = 1;
+var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE = 256;
+var SPAN_FLAGS_CONTEXT_IS_REMOTE = 512;
+function spanFlags(record) {
+ const traceFlags = parseInt(record.traceFlags, 16);
+ const w3c = Number.isFinite(traceFlags) ? 255 & traceFlags : TRACE_FLAGS_SAMPLED2;
+ return w3c | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE | (record.parentIsRemote ? SPAN_FLAGS_CONTEXT_IS_REMOTE : 0);
+}
+function wireString(value) {
+ if (typeof value == "string")
+ return sanitizeString(value);
+ try {
+ return sanitizeString(String(value));
+ } catch {
+ return UNSERIALIZABLE_VALUE;
+ }
+}
+function spanKindToOtlp(kind) {
+ if (kind && Object.prototype.hasOwnProperty.call(SPAN_KIND_TO_OTLP, kind))
+ return SPAN_KIND_TO_OTLP[kind];
+ return SPAN_KIND_TO_OTLP.internal;
+}
+function msToUnixNanoString(ms) {
+ let whole = Math.floor(ms);
+ let fractionalNanos = Math.round((ms - whole) * 1e6);
+ if (fractionalNanos >= 1e6) {
+ whole += 1;
+ fractionalNanos = 0;
+ }
+ return String(whole) + String(fractionalNanos).padStart(6, "0");
+}
+function toOtlpEvent(event, logger) {
+ const encoded = {
+ name: wireString(event.name),
+ timeUnixNano: msToUnixNanoString(event.timestamp)
+ };
+ if (event.attributes) {
+ const attributes = toOtlpKeyValueList(event.attributes, logger);
+ if (attributes.length)
+ encoded.attributes = attributes;
+ }
+ const dropped = nonNegativeCount(event.droppedAttributesCount);
+ if (dropped)
+ encoded.droppedAttributesCount = dropped;
+ return encoded;
+}
+function buildOtlpSpan(record, logger) {
+ const span = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ name: wireString(record.name),
+ kind: spanKindToOtlp(record.kind),
+ startTimeUnixNano: msToUnixNanoString(record.startTime),
+ endTimeUnixNano: msToUnixNanoString(record.endTime),
+ flags: spanFlags(record)
+ };
+ if (record.parentSpanId)
+ span.parentSpanId = record.parentSpanId;
+ if (record.traceState)
+ span.traceState = wireString(record.traceState);
+ const attributes = toOtlpKeyValueList(record.attributes, logger);
+ if (attributes.length)
+ span.attributes = attributes;
+ if (record.events.length)
+ span.events = record.events.map((event) => toOtlpEvent(event, logger));
+ const droppedAttributes = nonNegativeCount(record.droppedAttributesCount);
+ if (droppedAttributes)
+ span.droppedAttributesCount = droppedAttributes;
+ const droppedEvents = nonNegativeCount(record.droppedEventsCount);
+ if (droppedEvents)
+ span.droppedEventsCount = droppedEvents;
+ if (record.status)
+ span.status = {
+ code: SPAN_STATUS_TO_OTLP[record.status.code],
+ ...record.status.message && {
+ message: wireString(record.status.message)
+ }
+ };
+ return span;
+}
+function buildTracesResourceAttributes(config, sdkName, sdkVersion) {
+ return buildOtlpResourceAttributes(config, sdkName, sdkVersion);
+}
+function buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, logger) {
+ return {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes, logger)
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ spans
+ }
+ ]
+ }
+ ]
+ };
+}
+
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/index.mjs
+var MAX_RETRIES_PER_BATCH = 8;
+function clockNow() {
+ return monotonicNow() ?? Date.now();
+}
+function isOwnSpan(value) {
+ try {
+ return value instanceof PostHogSpan;
+ } catch {
+ return false;
+ }
+}
+function remoteContext(header, tracestate) {
+ const remote = parseTraceparent(header);
+ if (!remote)
+ return;
+ return {
+ traceId: remote.traceId,
+ parentSpanId: remote.spanId,
+ traceState: sanitizeTracestate(tracestate),
+ traceFlags: remote.flags,
+ isRemote: true
+ };
+}
+function looksLikeSpan(value) {
+ try {
+ return typeof value.traceparent == "function";
+ } catch {
+ return false;
+ }
+}
+function isSpanRecordShape(record) {
+ return !!record.attributes && typeof record.attributes == "object" && !Array.isArray(record.attributes) && Array.isArray(record.events) && record.name !== undefined && record.kind !== undefined && record.startTime !== undefined && record.endTime !== undefined;
+}
+function restoreField(record, field, value) {
+ if (record[field] !== value)
+ record[field] = value;
+}
+function withRestoredIdentity(hooked, original) {
+ try {
+ const descriptors = Object.getOwnPropertyDescriptors(hooked);
+ for (const field of [
+ "traceId",
+ "spanId",
+ "parentSpanId",
+ "traceState"
+ ])
+ descriptors[field] = {
+ value: original[field],
+ enumerable: true,
+ writable: true,
+ configurable: true
};
+ return Object.create(Object.getPrototypeOf(hooked), descriptors);
+ } catch {
+ return hooked;
+ }
+}
+
+class PostHogTraces {
+ constructor(_instance, _config, _logger, _getContext, _contextManager, _onSpanQueued) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._getContext = _getContext;
+ this._contextManager = _contextManager;
+ this._onSpanQueued = _onSpanQueued;
+ this._queue = [];
+ this._flushTimer = new FlushTimer(() => this._flushInBackground());
+ this._flushPromise = null;
+ this._droppedSinceWarning = 0;
+ this._lastDropWarningAt = 0;
+ this._dropReasons = new Set;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter = new RetryAfterWindow;
+ this._headBatchFailures = 0;
+ this._headBatchSize = 0;
+ this._headBatchChargeableAt = 0;
+ this._generation = 0;
+ this._liveSpans = new Map;
+ this._maxExportBatchSize = _config.maxExportBatchSize;
+ }
+ startSpan(name, options) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return inertSpan(options, this._contextManager.active());
+ const explicitParent = traceparentHeader(options?.parent);
+ if (explicitParent && typeof explicitParent != "string" && !isOwnSpan(explicitParent)) {
+ if (looksLikeSpan(explicitParent)) {
+ this._logger.debug("Span parent is not a span from this SDK; returning an inert span");
+ return inertSpan(options, this._contextManager.active());
+ }
+ this._logger.debug("Ignoring an unusable span parent");
+ }
+ const parent = this._resolveParent(explicitParent, options);
+ this._evictAgedSpans();
+ if (this._liveSpans.size >= this._config.maxLiveSpans) {
+ this._recordDrop(1, `the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`);
+ return inertSpan(options, this._contextManager.active());
+ }
+ const now = Date.now();
+ const startTime = resolveStartTime(options?.startTime, now, this._logger);
+ const spanId = newSpanId();
+ this._liveSpans.set(spanId, clockNow());
+ const autoAttributes = this._autoContextAttributes();
+ return new PostHogSpan({
+ traceId: parent?.traceId ?? newTraceId(),
+ spanId,
+ parentSpanId: parent?.parentSpanId,
+ traceState: parent?.traceState,
+ traceFlags: parent?.traceFlags,
+ parentIsRemote: parent?.isRemote,
+ name: sanitizeName(name, "Span name", this._config.maxAttributeValueLength, this._logger),
+ kind: options?.kind ?? "internal",
+ attributes: assignUserAttributes({
+ ...autoAttributes
+ }, options?.attributes),
+ autoAttributeKeys: Object.keys(autoAttributes),
+ maxAttributes: this._config.maxAttributesPerSpan,
+ maxEvents: this._config.maxEventsPerSpan,
+ maxAttributesPerEvent: this._config.maxAttributesPerEvent,
+ maxAttributeValueLength: this._config.maxAttributeValueLength,
+ startTime,
+ backdated: startTime !== now,
+ clockAnchor: toEpochMs(options?.startTime) === undefined ? parent?.clockAnchor : undefined
+ }, (record, autoKeys) => this._onSpanEnd(record, autoKeys), this._logger);
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const span = this.startSpan(name, options);
+ try {
+ const result = runWithActiveSpan(this._contextManager, span, fn);
+ if (isPromise(result))
+ return result.then((value) => {
+ span.end();
+ return value;
+ }, (error) => {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
+ });
+ span.end();
+ return result;
+ } catch (error) {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
+ }
+ }
+ getActiveSpan() {
+ return this._contextManager.active() ?? null;
+ }
+ get throttled() {
+ return this._retryAfter.isOpen();
+ }
+ async flush() {
+ for (;; ) {
+ if (!this._queue.length)
+ return;
+ const inFlight = this._flushPromise;
+ const removed = await (inFlight ?? this._startFlush());
+ if (!removed)
+ return;
+ }
+ }
+ _startFlush() {
+ this._flushTimer.clear();
+ const startedAtGeneration = this._generation;
+ const promise = Promise.resolve().then(() => startedAtGeneration === this._generation ? this._flushInner() : 0).finally(() => {
+ if (this._flushPromise === promise)
+ this._flushPromise = null;
+ this._armFlushTimerIfQueuedNoEarlierThan();
+ });
+ this._flushPromise = promise;
+ return promise;
+ }
+ reset() {
+ this._flushTimer.clear();
+ if (this._queue.length)
+ this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`);
+ this._queue = [];
+ this._liveSpans.clear();
+ this._flushPromise = null;
+ this._generation++;
+ this._maxExportBatchSize = this._config.maxExportBatchSize;
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ this._lastDropWarningAt = 0;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter.reset();
+ this._resetHeadBatchBudget();
+ }
+ _resetHeadBatchBudget() {
+ this._headBatchFailures = 0;
+ this._headBatchChargeableAt = 0;
+ }
+ _resolveParent(explicit, options) {
+ if (typeof explicit == "string") {
+ const remote = remoteContext(explicit, options?.tracestate);
+ if (!remote)
+ this._logger.debug("Ignoring malformed traceparent; starting a new trace");
+ return remote;
+ }
+ if (isOwnSpan(explicit))
+ return explicit.childContext();
+ const active = this._contextManager.active();
+ if (isOwnSpan(active))
+ return active.childContext();
+ if (active instanceof PassThroughSpan)
+ return remoteContext(active.traceparent(), active.tracestate() ?? undefined);
+ }
+ _autoContextAttributes() {
+ let context;
+ try {
+ context = this._getContext();
+ } catch (error) {
+ this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes", error);
+ return {};
+ }
+ const attributes = {};
+ if (context.distinctId)
+ attributes.posthogDistinctId = context.distinctId;
+ if (context.sessionId)
+ attributes.sessionId = context.sessionId;
+ if (context.currentUrl)
+ attributes["url.full"] = context.currentUrl;
+ if (context.screenName)
+ attributes["screen.name"] = context.screenName;
+ if (context.appState)
+ attributes["app.state"] = context.appState;
+ return attributes;
+ }
+ _recordCallbackError(span, error) {
+ if (!(span instanceof PostHogSpan))
+ return;
+ const { type, message, stack } = describeError(error);
+ span.addEvent("exception", {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
+ }
+ });
+ if (!span.statusIsExplicitlyOk)
+ span.setStatus("error", message);
+ }
+ _evictAgedSpans() {
+ const cutoff = clockNow() - this._config.maxSpanAgeMs;
+ let evicted = 0;
+ for (const [spanId, startedAt] of this._liveSpans) {
+ if (startedAt > cutoff)
+ break;
+ this._liveSpans.delete(spanId);
+ evicted++;
}
+ if (evicted)
+ this._recordDrop(evicted, `they were still live after ${this._config.maxSpanAgeMs}ms`);
}
- async _sendMetricsBatch(payload) {
- if (this.disabled)
- return {
- kind: "fatal",
- error: new Error("The client is disabled")
- };
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
+ _onSpanEnd(incoming, autoKeys) {
+ if (!this._liveSpans.delete(incoming.spanId))
+ return;
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return void this._recordDrop(1, "the user has opted out");
+ const record = this._runBeforeSpanSend(incoming, autoKeys);
+ if (!record)
+ return;
+ this._reportLimitDrops(record);
+ if (this._queue.length >= this._config.maxQueueSize)
+ return void this._recordDrop(1, `the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);
+ this._queue.push(record);
+ try {
+ this._onSpanQueued?.();
+ } catch (error) {
+ this._logger.debug("Span queue notification failed", error);
+ }
+ if (!(this._queue.length >= this._maxExportBatchSize) || this._consecutiveFlushFailures || this._retryAfter.isOpen())
+ this._armFlushTimerIfQueued();
+ else
+ this._flushInBackground();
+ }
+ _reportLimitDrops(record) {
+ const attributes = record.droppedAttributesCount ?? 0;
+ const events = record.droppedEventsCount ?? 0;
+ let eventAttributes = 0;
+ for (const event of record.events)
+ eventAttributes += event.droppedAttributesCount ?? 0;
+ if (attributes || events || eventAttributes)
+ this._logger.debug(`Span limits discarded data from "${record.name}": ${attributes} attributes, ${events} events, ${eventAttributes} event attributes`);
+ }
+ _runBeforeSpanSend(record, autoKeys) {
+ if (!this._config.beforeSpanSend.length)
+ return record;
+ const identity = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ parentSpanId: record.parentSpanId,
+ traceState: record.traceState
+ };
+ const originalTimes = {
+ startTime: record.startTime,
+ endTime: record.endTime
};
+ const originalDropped = {
+ attributes: record.droppedAttributesCount,
+ events: record.droppedEventsCount
+ };
+ const keysBeforeHook = Object.keys(record.attributes);
+ const originalPropagation = {
+ traceFlags: record.traceFlags,
+ parentIsRemote: record.parentIsRemote
+ };
+ const originalStatus = record.status && {
+ ...record.status
+ };
+ let hooked = record;
+ let current = record;
try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
+ for (const hook of this._config.beforeSpanSend) {
+ const result = hook(hooked);
+ if (!result) {
+ this._recordDrop(1, "beforeSpanSend dropped it");
+ return null;
}
- });
- return {
- kind: "ok"
- };
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (isPostHogFetchRetryableError(err))
- return {
- kind: "retry-later",
- error: err
- };
- return {
- kind: "fatal",
- error: err
+ hooked = this._keepSpanIdentity(result, identity);
+ }
+ const rebuilt = {
+ traceId: identity.traceId,
+ spanId: identity.spanId,
+ parentSpanId: identity.parentSpanId,
+ traceState: identity.traceState,
+ name: hooked.name,
+ kind: hooked.kind,
+ status: hooked.status,
+ attributes: hooked.attributes,
+ events: hooked.events,
+ startTime: hooked.startTime,
+ endTime: hooked.endTime,
+ traceFlags: originalPropagation.traceFlags,
+ parentIsRemote: originalPropagation.parentIsRemote,
+ droppedAttributesCount: originalDropped.attributes,
+ droppedEventsCount: originalDropped.events
};
+ current = rebuilt;
+ if (!isSpanRecordShape(current)) {
+ this._logger.debug("beforeSpanSend did not return a span record; dropping the span");
+ this._recordDrop(1, "beforeSpanSend returned an unusable record");
+ return null;
+ }
+ current.name = sanitizeName(current.name, "Span name", this._config.maxAttributeValueLength, this._logger);
+ if (current.status && current.status.code !== "ok" && current.status.code !== "error") {
+ this._logger.debug("beforeSpanSend set an unknown span status; keeping the original");
+ current.status = originalStatus;
+ }
+ current.startTime = toEpochMs(current.startTime) ?? originalTimes.startTime;
+ current.endTime = clampEndTime(toEpochMs(current.endTime) ?? originalTimes.endTime, current.startTime);
+ const sanitizedEvents = [];
+ for (const event of current.events)
+ try {
+ sanitizedEvents.push({
+ ...event,
+ name: sanitizeName(event.name, "Span event name", this._config.maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(event.timestamp, current.startTime, "event timestamp", this._logger)
+ });
+ } catch {
+ this._logger.debug("beforeSpanSend left an unreadable span event; dropping it");
+ }
+ current.events = sanitizedEvents;
+ applySpanLimits(current, autoKeys, this._config.maxAttributesPerSpan, this._config.maxEventsPerSpan, this._config.maxAttributesPerEvent, this._config.maxAttributeValueLength, keysBeforeHook);
+ return current;
+ } catch (error) {
+ this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed", error);
+ this._recordDrop(1, "beforeSpanSend failed");
+ return null;
}
}
- async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
- const body = options.body ? options.body : "";
- let reqByteLength = -1;
+ _keepSpanIdentity(hooked, original) {
+ if (hooked.traceId !== original.traceId || hooked.spanId !== original.spanId || hooked.parentSpanId !== original.parentSpanId)
+ this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");
try {
- reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
+ restoreField(hooked, "traceId", original.traceId);
+ restoreField(hooked, "spanId", original.spanId);
+ restoreField(hooked, "parentSpanId", original.parentSpanId);
+ restoreField(hooked, "traceState", original.traceState);
} catch {
- if (body instanceof Blob)
- reqByteLength = body.size;
- else if (body instanceof Uint8Array)
- reqByteLength = body.byteLength;
- else {
- const encoded = new TextEncoder().encode(body);
- reqByteLength = encoded.length;
- }
+ return withRestoredIdentity(hooked, original);
}
- const retriableOptions = {
- ...this._retryOptions,
- ...retryOptions
- };
- let attempt = 0;
- return await retriable(async () => {
- attempt++;
- const ctrl = new AbortController;
- const timeoutMs = requestTimeout ?? this.requestTimeout;
- const requestDeadline = Date.now() + timeoutMs;
- let timer;
- const deadline = new Promise((_resolve, reject) => {
- timer = safeSetTimeout(() => {
- const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
- timeoutError.name = "AbortError";
- reject(timeoutError);
- ctrl.abort(timeoutError);
- }, timeoutMs);
- });
- let res;
- let responseAccepted = false;
- let cancellation;
- const cancelBody = () => cancellation ??= (async () => {
- try {
- await res?.body?.cancel();
- } catch {}
- })();
+ return hooked;
+ }
+ _recordDrop(count, reason) {
+ this._droppedSinceWarning += count;
+ this._dropReasons.add(reason);
+ if (Date.now() - this._lastDropWarningAt >= this._config.flushIntervalMs)
+ this._warnAboutDrops();
+ }
+ _warnAboutDrops() {
+ if (!this._droppedSinceWarning)
+ return;
+ this._lastDropWarningAt = Date.now();
+ this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[
+ ...this._dropReasons
+ ].join("; ")}`);
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ }
+ _encodeBatch(batch) {
+ const encoded = [];
+ for (const record of batch)
try {
- let fetchPromise;
- try {
- fetchPromise = this.fetch(url, {
- signal: ctrl.signal,
- ...options
- });
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
+ encoded.push(buildOtlpSpan(record, this._logger));
+ } catch (error) {
+ this._logger.debug("Failed to encode a span; dropping it", error);
+ this._recordDrop(1, "its attributes could not be encoded");
+ }
+ return encoded;
+ }
+ _discardQueueIfConsentWithdrawn() {
+ if (!this._instance.isDisabled && !this._instance.optedOut)
+ return 0;
+ const discarded = this._queue.length;
+ this._queue = [];
+ this._resetHeadBatchBudget();
+ this._recordDrop(discarded, "the user has opted out");
+ this._warnAboutDrops();
+ return discarded;
+ }
+ async _flushInner() {
+ if (!this._queue.length)
+ return 0;
+ const discardedBeforeDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedBeforeDrain)
+ return discardedBeforeDrain;
+ const resourceAttributes = truncateAttributes(buildTracesResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._config.maxAttributeValueLength);
+ const scopeName = this._instance.getLibraryId();
+ const scopeVersion = this._instance.getLibraryVersion();
+ let remaining = this._queue.length;
+ let removed = 0;
+ let localCap = 1 / 0;
+ const generation = this._generation;
+ try {
+ while (remaining > 0 && this._queue.length > 0) {
+ const discardedMidDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedMidDrain)
+ return removed + discardedMidDrain;
+ const cap = this._headBatchFailures > 0 ? Math.min(this._maxExportBatchSize, this._headBatchSize) : this._maxExportBatchSize;
+ const size = Math.max(1, Math.min(cap, localCap, remaining, this._queue.length));
+ const batch = this._queue.slice(0, size);
+ const spans = this._encodeBatch(batch);
+ if (!spans.length) {
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._resetHeadBatchBudget();
+ continue;
}
- fetchPromise.then((lateResponse) => {
- if (ctrl.signal.aborted && !responseAccepted)
- Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
- }).catch(() => {});
- try {
- res = await Promise.race([
- fetchPromise,
- deadline
- ]);
- responseAccepted = true;
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
+ const chargeable = clockNow() >= this._headBatchChargeableAt && !this._retryAfter.isOpen();
+ const outcome = await this._instance._sendTracesBatch(buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, this._logger));
+ if (generation !== this._generation)
+ break;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "ok") {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ if (this._maxExportBatchSize < this._config.maxExportBatchSize)
+ this._maxExportBatchSize++;
+ continue;
}
- const isNoCors = options.mode === "no-cors";
- if (!isNoCors && (res.status < 200 || res.status >= 400))
- throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
- if (responseHandling.type === "successful-write") {
- try {
- await Promise.race([
- cancelBody(),
- deadline
- ]);
- } catch {}
- return;
+ if (outcome.kind === "too-large") {
+ if (size === 1) {
+ this._queue.splice(0, 1);
+ remaining -= 1;
+ removed += 1;
+ this._recordDrop(1, "it is too large for the ingestion endpoint");
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ continue;
+ }
+ const halved = Math.max(1, Math.floor(size / 2));
+ if (outcome.measuredLocally)
+ localCap = halved;
+ else
+ this._maxExportBatchSize = halved;
+ this._resetHeadBatchBudget();
+ this._logger.debug(`Batch too large; retrying the same spans in batches of ${halved}`);
+ continue;
}
- try {
- return await Promise.race([
- responseHandling.consume(res),
- deadline
- ]);
- } catch (e) {
- if (ctrl.signal.aborted)
- throw new PostHogFetchNetworkError(e);
- throw e;
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ this._headBatchSize = size;
+ if (chargeable) {
+ this._headBatchFailures++;
+ this._headBatchChargeableAt = clockNow() + this._nextFlushDelay();
+ }
+ if (this._headBatchFailures < MAX_RETRIES_PER_BATCH) {
+ this._logger.debug("Span export failed; retrying on the next flush", outcome.error);
+ return removed;
+ }
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, `the ingestion endpoint failed ${MAX_RETRIES_PER_BATCH} times in a row`);
+ if (this._retryAfter.isOpen())
+ return removed;
+ continue;
}
- } finally {
- clearTimeout(timer);
- if (ctrl.signal.aborted && res)
- cancelBody();
- }
- }, {
- ...retriableOptions,
- retryCheck: (error) => {
- const shouldRetry = retriableOptions.retryCheck(error);
- if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
- error.cancelResponseBody();
- return shouldRetry;
+ this._logger.debug("Dropping a span batch the ingestion endpoint rejected", outcome.error);
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, "the ingestion endpoint rejected the batch");
}
- });
+ return removed;
+ } finally {
+ this._warnAboutDrops();
+ }
}
- async _shutdown(shutdownTimeoutMs = 30000) {
- await this._initPromise;
- let hasTimedOut = false;
- this.clearFlushTimer();
- if (this.disabled)
+ _flushInBackground() {
+ if (this._backgroundFlush)
return;
- const doShutdown = async () => {
- try {
- await this.promiseQueue.join();
- while (true) {
- const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
- if (!hasQueuedEvents)
- break;
- const dequeuedBeforeFlush = this._dequeuedMessagesCount;
- await this.flush();
- if (hasTimedOut)
- break;
- if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
- this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
- break;
- }
- }
- } catch (e) {
- if (!isPostHogFetchError(e))
- throw e;
- await logFlushError(e);
- }
- };
- return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
- this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
- shutdownTimeoutMs
- });
- hasTimedOut = true;
+ this._backgroundFlush = this.flush().catch((error) => {
+ this._logger.debug("Background span flush failed", error);
+ }).finally(() => {
+ this._backgroundFlush = undefined;
+ this._armFlushTimerIfQueuedNoEarlierThan();
});
}
- async shutdown(shutdownTimeoutMs = 30000) {
- if (this.shutdownPromise)
- this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
- else
- this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
- this.shutdownPromise = null;
- });
- return this.shutdownPromise;
+ _armFlushTimerIfQueued() {
+ if (this._flushTimer.pending || !this._queue.length)
+ return;
+ this._flushTimer.arm(this._nextFlushDelay());
+ }
+ _armFlushTimerIfQueuedNoEarlierThan() {
+ if (!this._queue.length)
+ return;
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ }
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
+ }
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/context.mjs
+class SyncSpanContextManager {
+ active() {
+ return this._active;
+ }
+ with(span, fn) {
+ const previous = this._active;
+ this._active = span;
+ try {
+ return fn();
+ } finally {
+ this._active = previous;
+ }
+ }
+}
+// ../../../../../node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/config.mjs
+var DEFAULT_FLUSH_INTERVAL_MS2 = 5000;
+var DEFAULT_MAX_EXPORT_BATCH_SIZE = 512;
+var DEFAULT_MAX_QUEUE_SIZE = 2048;
+var DEFAULT_MAX_ATTRIBUTES_PER_SPAN = 128;
+var DEFAULT_MAX_EVENTS_PER_SPAN = 128;
+var DEFAULT_MAX_ATTRIBUTES_PER_EVENT = 128;
+var DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 8192;
+var DEFAULT_MAX_LIVE_SPANS = 1e4;
+var DEFAULT_MAX_SPAN_AGE_MS = 3600000;
+function positiveInteger(value, fallback) {
+ return typeof value == "number" && Number.isInteger(value) && value >= 1 ? value : fallback;
+}
+var IDENTITY_KEYS = [
+ "service.name",
+ "service.version",
+ "deployment.environment"
+];
+function withUsableIdentityKeys(attributes) {
+ if (!attributes || typeof attributes != "object" || Array.isArray(attributes))
+ return;
+ try {
+ if (IDENTITY_KEYS.every((key) => !(key in attributes) || typeof attributes[key] == "string"))
+ return attributes;
+ const usable = {
+ ...attributes
+ };
+ for (const key of IDENTITY_KEYS)
+ if (key in usable && typeof usable[key] != "string")
+ delete usable[key];
+ return usable;
+ } catch {
+ return;
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
+function resolveBeforeSpanSend(beforeSpanSend, logger) {
+ if (!beforeSpanSend)
+ return [];
+ const supplied = [
+ beforeSpanSend
+ ].flat().filter((hook) => Boolean(hook));
+ const hooks = supplied.filter((hook) => typeof hook == "function");
+ if (hooks.length !== supplied.length)
+ logger?.critical(`beforeSpanSend: ignoring ${supplied.length - hooks.length} of ${supplied.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);
+ return hooks;
+}
+function resolveTracesConfig(config, hostResourceAttributes, logger) {
+ const resourceAttributes = assignUserAttributes({
+ ...hostResourceAttributes
+ }, withUsableIdentityKeys(config?.resourceAttributes));
+ const maxExportBatchSize = positiveInteger(config?.maxExportBatchSize, DEFAULT_MAX_EXPORT_BATCH_SIZE);
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSpanSend: resolveBeforeSpanSend(config?.beforeSpanSend, logger),
+ maxAttributesPerSpan: positiveInteger(config?.maxAttributesPerSpan, DEFAULT_MAX_ATTRIBUTES_PER_SPAN),
+ maxEventsPerSpan: positiveInteger(config?.maxEventsPerSpan, DEFAULT_MAX_EVENTS_PER_SPAN),
+ maxAttributesPerEvent: DEFAULT_MAX_ATTRIBUTES_PER_EVENT,
+ maxAttributeValueLength: positiveInteger(config?.maxAttributeValueLength, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH),
+ flushIntervalMs: positiveInteger(config?.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS2),
+ maxExportBatchSize,
+ maxQueueSize: Math.max(positiveInteger(config?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE), maxExportBatchSize),
+ maxLiveSpans: positiveInteger(config?.maxLiveSpans, DEFAULT_MAX_LIVE_SPANS),
+ maxSpanAgeMs: positiveInteger(config?.maxSpanAgeMs, DEFAULT_MAX_SPAN_AGE_MS)
+ };
+}
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
import { constants as constants2 } from "node:fs";
import { open as promises_open } from "node:fs/promises";
import { isAbsolute } from "node:path";
@@ -4128,7 +6527,7 @@ function snipLine(line, colno) {
return newLine;
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
import { isAbsolute as isAbsolute2, relative, sep as sep2 } from "path";
function createRelativePathModifier(basePath = process.cwd()) {
const isWindows = sep2 === "\\";
@@ -4144,10 +6543,10 @@ function createRelativePathModifier(basePath = process.cwd()) {
};
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
-var version = "5.51.1";
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
+var version = "5.52.4";
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
var FeatureFlagError2 = {
ERRORS_WHILE_COMPUTING: "errors_while_computing_flags",
FLAG_MISSING: "flag_missing",
@@ -4155,7 +6554,7 @@ var FeatureFlagError2 = {
UNKNOWN_ERROR: "unknown_error"
};
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
class FeatureFlagEvaluations {
constructor(init) {
this._host = init.host;
@@ -4288,23 +6687,8 @@ class FeatureFlagEvaluations {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
-async function hashSHA1(text) {
- const subtle = globalThis.crypto?.subtle;
- if (!subtle)
- throw new Error("SubtleCrypto API not available");
- const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
-}
-
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
-var SIXTY_SECONDS = 60000;
-var LONG_SCALE = 1152921504606847000;
-var NULL_VALUES_ALLOWED_OPERATORS = [
- "is_not",
- "is_set"
-];
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
+var SIXTY_SECONDS = 60000;
class ClientError extends Error {
constructor(message) {
@@ -4321,13 +6705,6 @@ function setCustomErrorPrototype(error, constructor) {
Object.setPrototypeOf(error, constructor.prototype);
}
-class InconclusiveMatchError extends Error {
- constructor(message) {
- super(message);
- setCustomErrorPrototype(this, InconclusiveMatchError);
- }
-}
-
class RequiresServerEvaluation extends Error {
constructor(message) {
super(message);
@@ -4341,6 +6718,7 @@ class FeatureFlagsPoller {
this.shouldBeginExponentialBackoff = false;
this.backOffCount = 0;
this.pollerStopped = false;
+ this.filteredOutFlagKeys = new Set;
this.pollingInterval = pollingInterval;
this.personalApiKey = personalApiKey;
this.featureFlags = [];
@@ -4359,6 +6737,7 @@ class FeatureFlagsPoller {
this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
this.cacheProvider = options.cacheProvider;
this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
+ this.evaluationContexts = options.evaluationContexts;
this.loadFeatureFlags();
}
debug(enabled = true) {
@@ -4490,23 +6869,7 @@ class FeatureFlagsPoller {
return distinctId;
}
getFeatureFlagPayload(key, flagValue) {
- let payload = null;
- if (flagValue !== false && flagValue != null) {
- if (typeof flagValue == "boolean")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
- else if (typeof flagValue == "string")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
- if (payload != null) {
- if (typeof payload == "object")
- return payload;
- if (typeof payload == "string")
- try {
- return JSON.parse(payload);
- } catch {}
- return payload;
- }
- }
- return null;
+ return resolveFeatureFlagPayload(this.featureFlagsByKey?.[key]?.filters?.payloads, flagValue);
}
async evaluateFlagDependency(property, properties, evaluationContext) {
const { evaluationCache } = evaluationContext;
@@ -4533,6 +6896,8 @@ class FeatureFlagsPoller {
}
else
evaluationCache[depFlagKey] = false;
+ else if (this.filteredOutFlagKeys.has(depFlagKey))
+ evaluationCache[depFlagKey] = false;
else
throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
}
@@ -4585,8 +6950,11 @@ class FeatureFlagsPoller {
result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
break;
}
- if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound") {
+ if (isInconclusive)
+ break;
return false;
+ }
} catch (e) {
if (e instanceof RequiresServerEvaluation)
throw e;
@@ -4621,36 +6989,33 @@ class FeatureFlagsPoller {
if (rolloutPercentage == undefined)
return "match";
}
- if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
+ if (rolloutPercentage != null && await getFeatureFlagHash(flag.key, bucketingValue) > rolloutPercentage / 100)
return "out_of_rollout_bound";
return "match";
}
async getMatchingVariant(flag, bucketingValue) {
- const hashValue = await _hash(flag.key, bucketingValue, "variant");
- const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
- if (matchingVariant)
- return matchingVariant.key;
+ return getFeatureFlagVariant(flag.key, bucketingValue, flag.filters?.multivariate?.variants || []);
}
variantLookupTable(flag) {
- const lookupTable = [];
- let valueMin = 0;
- let valueMax = 0;
- const flagFilters = flag.filters || {};
- const multivariates = flagFilters.multivariate?.variants || [];
- multivariates.forEach((variant) => {
- valueMax = valueMin + variant.rollout_percentage / 100;
- lookupTable.push({
- valueMin,
- valueMax,
- key: variant.key
- });
- valueMin = valueMax;
+ return getFeatureFlagVariantLookupTable(flag.filters?.multivariate?.variants || []);
+ }
+ filterFlagsByEvaluationContexts(flags) {
+ if (!this.evaluationContexts || this.evaluationContexts.length === 0)
+ return flags;
+ const contexts = new Set(this.evaluationContexts);
+ return flags.filter((flag) => {
+ const tags = flag.evaluation_contexts ?? flag.evaluation_tags;
+ if (!tags || tags.length === 0)
+ return true;
+ return tags.some((tag) => contexts.has(tag));
});
- return lookupTable;
}
updateFlagState(flagData) {
- this.featureFlags = flagData.flags;
- this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const flags = this.filterFlagsByEvaluationContexts(flagData.flags);
+ this.featureFlags = flags;
+ this.featureFlagsByKey = flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const keptKeys = new Set(flags.map((flag) => flag.key));
+ this.filteredOutFlagKeys = new Set(flagData.flags.filter((flag) => !keptKeys.has(flag.key)).map((flag) => flag.key));
this.groupTypeMapping = flagData.groupTypeMapping;
this.cohorts = flagData.cohorts;
this.loadedSuccessfullyOnce = true;
@@ -4672,7 +7037,7 @@ class FeatureFlagsPoller {
this.updateFlagState(cached);
this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(cached.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
return true;
}
return false;
@@ -4750,6 +7115,7 @@ class FeatureFlagsPoller {
console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
this.featureFlags = [];
this.featureFlagsByKey = {};
+ this.filteredOutFlagKeys = new Set;
this.groupTypeMapping = {};
this.cohorts = {};
this.onMinimalFlagCalledEvents?.(false);
@@ -4781,7 +7147,7 @@ class FeatureFlagsPoller {
this.onError?.(new Error(`Failed to store in cache: ${err}`));
}
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(flagData.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
break;
}
default:
@@ -4867,136 +7233,10 @@ class FeatureFlagsPoller {
}
}
}
-async function _hash(key, bucketingValue, salt = "") {
- const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
- return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
-}
function matchProperty(property, propertyValues, warnFunction) {
- const key = property.key;
- const value = property.value;
- const operator = property.operator || "exact";
- if (key in propertyValues) {
- if (operator === "is_not_set")
- return false;
- } else {
- if (operator === "is_not_set")
- return true;
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
- }
- const overrideValue = propertyValues[key];
- if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
- if (warnFunction)
- warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
- return false;
- }
- function computeExactMatch(value, overrideValue) {
- if (Array.isArray(value))
- return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
- return String(value).toLowerCase() === String(overrideValue).toLowerCase();
- }
- function compare(lhs, rhs, operator) {
- if (operator === "gt")
- return lhs > rhs;
- if (operator === "gte")
- return lhs >= rhs;
- if (operator === "lt")
- return lhs < rhs;
- if (operator === "lte")
- return lhs <= rhs;
- throw new Error(`Invalid operator: ${operator}`);
- }
- switch (operator) {
- case "exact":
- return computeExactMatch(value, overrideValue);
- case "is_not":
- return !computeExactMatch(value, overrideValue);
- case "is_set":
- return key in propertyValues;
- case "icontains":
- return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "not_icontains":
- return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "starts_with":
- return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "not_starts_with":
- return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "ends_with":
- return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "not_ends_with":
- return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
- case "not_regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
- case "gt":
- case "gte":
- case "lt":
- case "lte": {
- const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
- let parsedOverride;
- parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : NaN;
- if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
- return compare(parsedOverride, parsedValue, operator);
- return compare(String(overrideValue), String(value), operator);
- }
- case "is_date_after":
- case "is_date_before": {
- if (typeof value == "boolean")
- throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
- if (parsedDate == null)
- parsedDate = convertToDateTime(value);
- if (parsedDate == null)
- throw new InconclusiveMatchError(`Invalid date: ${value}`);
- const overrideDate = convertToDateTime(overrideValue);
- if ([
- "is_date_before"
- ].includes(operator))
- return overrideDate < parsedDate;
- return overrideDate > parsedDate;
- }
- case "semver_eq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp === 0;
- }
- case "semver_neq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp !== 0;
- }
- case "semver_gt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp > 0;
- }
- case "semver_gte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp >= 0;
- }
- case "semver_lt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp < 0;
- }
- case "semver_lte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp <= 0;
- }
- case "semver_tilde": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeTildeBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_caret": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeCaretBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_wildcard": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeWildcardBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- default:
- throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
- }
+ return matchFeatureFlagProperty(property, propertyValues, {
+ warnFunction
+ });
}
function checkCohortExists(cohortId, cohortProperties) {
if (!(cohortId in cohortProperties))
@@ -5076,181 +7316,8 @@ async function matchPropertyGroup(propertyGroup, propertyValues, cohortPropertie
throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
return propertyGroupType === "AND";
}
-function isValidRegex(regex) {
- try {
- new RegExp(regex);
- return true;
- } catch (err) {
- return false;
- }
-}
-function parseSemverNumericIdentifier(part, raw) {
- if (!/^\d+$/.test(part))
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- if (part.length > 1 && part[0] === "0")
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- return parseInt(part, 10);
-}
-function parseSemver(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const baseVersion = text.split("-")[0].split("+")[0];
- if (!baseVersion || baseVersion.startsWith("."))
- throw new InconclusiveMatchError(`Invalid semver: ${value}`);
- const parts = baseVersion.split(".");
- const parsePart = (part) => {
- if (part === undefined || part === "")
- return 0;
- return parseSemverNumericIdentifier(part, value);
- };
- const major = parsePart(parts[0]);
- const minor = parsePart(parts[1]);
- const patch = parsePart(parts[2]);
- return [
- major,
- minor,
- patch
- ];
-}
-function compareSemverTuples(a, b) {
- for (let i = 0;i < 3; i++) {
- if (a[i] < b[i])
- return -1;
- if (a[i] > b[i])
- return 1;
- }
- return 0;
-}
-function computeTildeBounds(value) {
- const parsed = parseSemver(value);
- const lower = [
- parsed[0],
- parsed[1],
- parsed[2]
- ];
- const upper = [
- parsed[0],
- parsed[1] + 1,
- 0
- ];
- return {
- lower,
- upper
- };
-}
-function computeCaretBounds(value) {
- const parsed = parseSemver(value);
- const [major, minor, patch] = parsed;
- const lower = [
- major,
- minor,
- patch
- ];
- let upper;
- upper = major > 0 ? [
- major + 1,
- 0,
- 0
- ] : minor > 0 ? [
- 0,
- minor + 1,
- 0
- ] : [
- 0,
- 0,
- patch + 1
- ];
- return {
- lower,
- upper
- };
-}
-function computeWildcardBounds(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
- if (!cleanedText)
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- const parts = cleanedText.split(".");
- const parseWildcardPart = (part) => {
- try {
- return parseSemverNumericIdentifier(part, value);
- } catch {
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- }
- };
- const major = parseWildcardPart(parts[0]);
- let lower;
- let upper;
- if (parts.length === 1) {
- lower = [
- major,
- 0,
- 0
- ];
- upper = [
- major + 1,
- 0,
- 0
- ];
- } else {
- const minor = parseWildcardPart(parts[1]);
- lower = [
- major,
- minor,
- 0
- ];
- upper = [
- major,
- minor + 1,
- 0
- ];
- }
- return {
- lower,
- upper
- };
-}
-function convertToDateTime(value) {
- if (value instanceof Date)
- return value;
- if (typeof value == "string" || typeof value == "number") {
- const date = new Date(value);
- if (!isNaN(date.valueOf()))
- return date;
- throw new InconclusiveMatchError(`${value} is in an invalid date format`);
- }
- throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
-}
-function relativeDateParseForFeatureFlagMatching(value) {
- const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
- const match = value.match(regex);
- const parsedDt = new Date(new Date().toISOString());
- if (!match)
- return null;
- {
- if (!match.groups)
- return null;
- const number = parseInt(match.groups["number"]);
- if (number >= 1e4)
- return null;
- const interval = match.groups["interval"];
- if (interval == "h")
- parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
- else if (interval == "d")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
- else if (interval == "w")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
- else if (interval == "m")
- parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
- else {
- if (interval != "y")
- return null;
- parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
- }
- return parsedDt;
- }
-}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
var UNHANDLED_REJECTION_OPTION_NAMES = [
"--unhandled-rejections",
"--unhandled_rejections"
@@ -5348,7 +7415,7 @@ function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJEC
});
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
var SHUTDOWN_TIMEOUT = 2000;
class error_tracking_ErrorTracking {
@@ -5418,8 +7485,9 @@ class error_tracking_ErrorTracking {
this._rateLimiter.stop();
}
}
+var error_tracking_default = error_tracking_ErrorTracking;
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
class PostHogMemoryStorage {
getProperty(key) {
return this._memoryStorage[key];
@@ -5432,16 +7500,16 @@ class PostHogMemoryStorage {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
function isCaptureMode(value) {
return value === "v0" || value === "v1";
}
function resolveCaptureMode() {
- const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
+ const envMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
return isCaptureMode(envMode) ? envMode : "v0";
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
var AI_EVENT_PREFIX = "$ai_";
var ANALYTICS_ROUTE = "analytics";
var AI_ROUTE = "ai";
@@ -5449,7 +7517,7 @@ function isLegacyOnlyEvent(message) {
return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
class CaptureV1Error extends Error {
constructor({ requestId, drops, retryExhausted, cause }) {
super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = "CaptureV1Error";
@@ -5466,7 +7534,7 @@ class CaptureV1Error extends Error {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
function coerceBool(value) {
if (typeof value == "boolean")
return value;
@@ -5581,7 +7649,7 @@ function buildV1Batch(messages, { createdAt, historicalMigration }) {
return batch;
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
var V1_ANALYTICS_PATH = "/i/v1/analytics/events";
var DEFAULT_MAX_BACKOFF_MS = 30000;
var RETRYABLE_STATUSES = new Set([
@@ -5834,13 +7902,13 @@ class V1CaptureSender {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
var AI_CAPTURE_ROUTE = "ai-capture";
var AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/";
var AI_MAX_EVENT_BYTES = 8388608;
var AI_BATCH_TARGET_BYTES = 5242880;
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
var encoder = new TextEncoder;
function eventByteSize(message) {
return encoder.encode(safeJsonStringify(message)).length;
@@ -5877,7 +7945,7 @@ function partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBa
};
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
var MINIMUM_POLLING_INTERVAL = 100;
var THIRTY_SECONDS = 30000;
var MAX_CACHE_SIZE = 50000;
@@ -5963,10 +8031,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
},
customHeaders: this.getCustomHeaders(),
cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
- strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
+ strictLocalEvaluation: normalizedOptions.strictLocalEvaluation,
+ evaluationContexts: normalizedOptions.evaluationContexts ?? normalizedOptions.evaluationEnvironments
});
}
- this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
+ this.errorTracking = new error_tracking_default(this, normalizedOptions, this._logger);
this.distinctIdHasSentFlagCalls = {};
this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
}
@@ -5974,8 +8043,26 @@ class PostHogBackendClient extends PostHogCoreStateless {
super.enqueue(type, message, options, explicitRoute);
this.scheduleDebouncedFlush();
}
+ _flushEventsAndSpans(skipThrottledSpans = false) {
+ const events = this.flushWithPendingPromises();
+ if (!this._traces || skipThrottledSpans && this._traces.throttled)
+ return events;
+ return allSettled([
+ events,
+ this._traces.flush().catch(() => {})
+ ]).then(([eventsResult]) => {
+ if (eventsResult.status === "rejected")
+ throw eventsResult.reason;
+ });
+ }
+ flushAutomatic() {
+ return this._flushKeepingRuntimeAlive(true);
+ }
async flush() {
- const flushPromise = this.flushWithPendingPromises();
+ return this._flushKeepingRuntimeAlive(false);
+ }
+ _flushKeepingRuntimeAlive(skipThrottledSpans) {
+ const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
const waitUntil = this.options.waitUntil;
if (waitUntil && !this._waitUntilCycle)
try {
@@ -6028,7 +8115,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
async resolveWaitUntilFlush() {
const resolve = this._consumeWaitUntilCycle();
try {
- await this.flushWithPendingPromises();
+ await this._flushEventsAndSpans();
} catch {} finally {
resolve?.();
}
@@ -6130,9 +8217,51 @@ class PostHogBackendClient extends PostHogCoreStateless {
this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
return this._metrics;
}
+ initializeSpanContextManager() {
+ return new SyncSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return {};
+ }
+ get _spanContextManager() {
+ if (!this._spanContext)
+ this._spanContext = this.initializeSpanContextManager();
+ return this._spanContext;
+ }
+ get _tracesPipeline() {
+ if (!this.options.traces)
+ return;
+ if (!this._traces)
+ this._traces = new PostHogTraces(this, resolveTracesConfig(this.options.traces, this.hostResourceAttributes(), this._logger), this._logger, () => this._tracingContext(), this._spanContextManager, () => this.scheduleDebouncedFlush());
+ return this._traces;
+ }
+ _tracingContext() {
+ const context = this.context?.get();
+ return {
+ distinctId: context?.distinctId,
+ sessionId: context?.sessionId
+ };
+ }
+ startSpan(name, options) {
+ return this._tracesPipeline?.startSpan(name, options) ?? inertSpan(options, this._spanContextManager.active());
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const pipeline = this._tracesPipeline;
+ if (!pipeline)
+ return runWithActiveSpan(this._spanContextManager, inertSpan(options, this._spanContextManager.active()), fn);
+ return options ? pipeline.withSpan(name, options, fn) : pipeline.withSpan(name, fn);
+ }
+ getActiveSpan() {
+ return this._spanContextManager.active() ?? null;
+ }
getCustomUserAgent() {
return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
}
+ getEvaluationRuntime() {
+ return "server";
+ }
getCommonEventProperties() {
const commonProperties = super.getCommonEventProperties();
if (this.options.isServer ?? true)
@@ -6620,7 +8749,16 @@ class PostHogBackendClient extends PostHogCoreStateless {
flags: {}
});
}
- const { groups, disableGeoip, flagKeys } = resolvedOptions || {};
+ const { groups, disableGeoip } = resolvedOptions || {};
+ const flagKeys = resolvedOptions?.flagKeys ?? undefined;
+ if (flagKeys?.length === 0)
+ return new FeatureFlagEvaluations({
+ host: this._getFeatureFlagEvaluationsHost(),
+ distinctId: resolvedDistinctId,
+ groups,
+ disableGeoip,
+ flags: {}
+ });
let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};
const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
personProperties = adjustedProperties.allPersonProperties;
@@ -6874,6 +9012,10 @@ class PostHogBackendClient extends PostHogCoreStateless {
await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
this._metrics.reset();
}
+ if (this._traces) {
+ await raceWithTimeout(this._traces.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
+ this._traces.reset();
+ }
try {
return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
} finally {
@@ -7002,9 +9144,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
};
}
captureException(error, distinctId, additionalProperties, uuid, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
...msg,
@@ -7014,9 +9156,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
}
}
async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ return this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this.captureImmediate({
...msg,
@@ -7126,7 +9268,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
import { AsyncLocalStorage } from "node:async_hooks";
class PostHogContext {
@@ -7157,7 +9299,22 @@ class PostHogContext {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/span-context.node.mjs
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
+
+class AsyncLocalStorageSpanContextManager {
+ active() {
+ return this._storage.getStore();
+ }
+ with(span, fn) {
+ return this._storage.run(span, fn);
+ }
+ constructor() {
+ this._storage = new AsyncLocalStorage2;
+ }
+}
+
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
import { gzip } from "node:zlib";
import { promisify } from "node:util";
var gzipAsync = promisify(gzip);
@@ -7172,7 +9329,19 @@ async function gzipCompress2(input, isDebug = true) {
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/host-os.node.mjs
+import { platform, release as release2 } from "node:os";
+function hostOsResourceAttributes() {
+ let osName;
+ let osVersion;
+ try {
+ osName = platform();
+ osVersion = release2();
+ } catch {}
+ return osResourceAttributes(osName, osVersion);
+}
+
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
var NAME = "posthog-node";
function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
"error"
@@ -7227,7 +9396,9 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
};
}
class PostHogSentryIntegration {
- static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ static {
+ this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ }
constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
this.name = NAME;
this.name = NAME;
@@ -7243,7 +9414,7 @@ class PostHogSentryIntegration {
};
}
}
-// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
+// ../../../../../node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
class PostHog extends PostHogBackendClient {
getLibraryId() {
return "posthog-node";
@@ -7254,6 +9425,12 @@ class PostHog extends PostHogBackendClient {
initializeContext() {
return new PostHogContext;
}
+ initializeSpanContextManager() {
+ return new AsyncLocalStorageSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return hostOsResourceAttributes();
+ }
createErrorPropertiesBuilder() {
return new ErrorPropertiesBuilder([
new EventCoercer,
diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.json
index 002a912e..504db9a7 100644
--- a/plugins/omo/components/telemetry/hooks/hooks.json
+++ b/plugins/omo/components/telemetry/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Recording Session Telemetry"
+ "statusMessage": "(OmO 5.0.0-beta.81) Recording Session Telemetry"
}
]
}
diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.json
index 8fc5bfdc..75d921f1 100644
--- a/plugins/omo/components/telemetry/package.json
+++ b/plugins/omo/components/telemetry/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-telemetry",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.",
"type": "module",
"packageManager": "[email protected]",
@@ -43,11 +43,12 @@
"check": "tsc --noEmit && biome check . && npm run build"
},
"devDependencies": {
+ "@vitest/coverage-v8": "5.0.1",
"@oh-my-opencode/telemetry-core": "file:../../../../telemetry-core",
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.json
index 3236366c..e049d4d9 100644
--- a/plugins/omo/components/ultrawork/hooks/hooks.json
+++ b/plugins/omo/components/ultrawork/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ultrawork Trigger"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ultrawork Trigger"
}
]
}
diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.json
index 45e530af..ffffd50e 100644
--- a/plugins/omo/components/ultrawork/package.json
+++ b/plugins/omo/components/ultrawork/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-ultrawork",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex plugin that injects the ultrawork orchestration directive and ships LazyCodex planning, review, QA, and gate agent roles.",
"type": "module",
"packageManager": "[email protected]",
@@ -43,11 +43,12 @@
"NOTICE"
],
"devDependencies": {
- "@biomejs/biome": "2.5.9",
+ "@vitest/coverage-v8": "5.0.1",
+ "@biomejs/biome": "2.5.14",
"@oh-my-opencode/prompts-core": "file:../../../../prompts-core",
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json
index 6fa4e4dc..c504f9d4 100644
--- a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json
+++ b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ulw-Execute Continuation"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ulw-Execute Continuation"
}
]
}
diff --git a/plugins/omo/components/ulw-execute-continuation/package.json b/plugins/omo/components/ulw-execute-continuation/package.json
index ae412a96..ccac6716 100644
--- a/plugins/omo/components/ulw-execute-continuation/package.json
+++ b/plugins/omo/components/ulw-execute-continuation/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-ulw-execute-continuation",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex Stop hook continuation injector for omo-codex ulw-execute plans.",
"type": "module",
"packageManager": "[email protected]",
@@ -42,10 +42,11 @@
"NOTICE"
],
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@vitest/coverage-v8": "5.0.1",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.json
index ccd788a1..03cbaa29 100644
--- a/plugins/omo/components/ulw-loop/hooks/hooks.json
+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit --with-ultrawork",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ulw-Loop Steering"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ulw-Loop Steering"
}
]
}
@@ -20,7 +20,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Recording Spawn Admission"
+ "statusMessage": "(OmO 5.0.0-beta.81) Recording Spawn Admission"
}
]
}
@@ -33,7 +33,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Enforcing Unlimited Ulw-Loop Budget"
+ "statusMessage": "(OmO 5.0.0-beta.81) Enforcing Unlimited Ulw-Loop Budget"
}
]
},
@@ -44,7 +44,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Guarding Ulw-Loop Spawns"
+ "statusMessage": "(OmO 5.0.0-beta.81) Guarding Ulw-Loop Spawns"
}
]
}
@@ -56,7 +56,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ulw-Loop Resume"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ulw-Loop Resume"
}
]
}
diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.json
index de42e157..be9c1db6 100644
--- a/plugins/omo/components/ulw-loop/package.json
+++ b/plugins/omo/components/ulw-loop/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-ulw-loop",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
"type": "module",
"packageManager": "[email protected]",
@@ -47,10 +47,11 @@
"check": "tsc --noEmit && biome check . && npm run build"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@vitest/coverage-v8": "5.0.1",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
diff --git a/plugins/omo/dist/cli-node/index.js b/plugins/omo/dist/cli-node/index.js
index 5f083ed7..b2557746 100755
--- a/plugins/omo/dist/cli-node/index.js
+++ b/plugins/omo/dist/cli-node/index.js
@@ -65,7 +65,7 @@ var package_default;
var init_package = __esm(() => {
package_default = {
name: "oh-my-opencode",
- version: "5.0.0-beta.80",
+ version: "5.0.0-beta.81",
description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",
main: "./dist/index.js",
types: "dist/index.d.ts",
@@ -229,25 +229,25 @@ var init_package = __esm(() => {
},
homepage: "https://github.com/code-yeongyu/oh-my-openagent#readme",
dependencies: {
- "@clack/prompts": "^1.7.0",
+ "@clack/prompts": "^1.8.1",
"@modelcontextprotocol/sdk": "^1.30.0",
- "@opencode-ai/plugin": "1.18.22",
- "@opencode-ai/sdk": "1.18.22",
- "@opentui/core": "^0.5.8",
- "@opentui/keymap": "^0.5.8",
- "@opentui/solid": "^0.5.8",
+ "@opencode-ai/plugin": "1.18.31",
+ "@opencode-ai/sdk": "1.18.31",
+ "@opentui/core": "^0.5.11",
+ "@opentui/keymap": "^0.5.11",
+ "@opentui/solid": "^0.5.11",
commander: "^15.0.0",
"detect-libc": "^2.1.2",
diff: "^9.0.0",
- "js-yaml": "^5.0.0",
+ "js-yaml": "^5.4.2",
"jsonc-parser": "^3.3.1",
picocolors: "^1.1.1",
picomatch: "^4.0.7",
- "posthog-node": "^5.51.1",
- zod: "^4.4.3"
+ "posthog-node": "^5.52.4",
+ zod: "^4.6.5"
},
devDependencies: {
- "@code-yeongyu/senpi": "2026.9.20",
+ "@code-yeongyu/senpi": "2026.9.21-2",
"@oh-my-opencode/agents-md-core": "workspace:*",
"@oh-my-opencode/ast-grep-mcp": "workspace:*",
"@oh-my-opencode/boulder-state": "workspace:*",
@@ -282,34 +282,36 @@ var init_package = __esm(() => {
"@xterm/xterm": "^6.0.0",
"bun-types": "1.4.2",
"node-pty": "^1.1.0",
- "puppeteer-core": "^25.8.0",
+ "puppeteer-core": "^25.11.0",
typescript: "^7.0.2"
},
optionalDependencies: {
- "oh-my-opencode-darwin-arm64": "5.0.0-beta.80",
- "oh-my-opencode-darwin-x64": "5.0.0-beta.80",
- "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.80",
- "oh-my-opencode-linux-arm64": "5.0.0-beta.80",
- "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64-musl": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.80",
- "oh-my-opencode-windows-arm64": "5.0.0-beta.80",
- "oh-my-opencode-windows-x64": "5.0.0-beta.80",
- "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.80"
+ "oh-my-opencode-darwin-arm64": "5.0.0-beta.81",
+ "oh-my-opencode-darwin-x64": "5.0.0-beta.81",
+ "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.81",
+ "oh-my-opencode-linux-arm64": "5.0.0-beta.81",
+ "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64-musl": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.81",
+ "oh-my-opencode-windows-arm64": "5.0.0-beta.81",
+ "oh-my-opencode-windows-x64": "5.0.0-beta.81",
+ "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.81"
},
overrides: {
"@earendil-works/pi-agent-core": "0.84.2",
"@earendil-works/pi-ai": "0.84.2",
"@earendil-works/pi-coding-agent": "0.84.2",
"@earendil-works/pi-tui": "0.84.2",
- hono: "^4.12.18",
- "@hono/node-server": "^1.19.13",
- "express-rate-limit": "^8.5.1",
- "fast-uri": "^3.1.2",
+ hono: "^4.13.8",
+ "@hono/node-server": "2.1.1",
+ "express-rate-limit": "^8.7.0",
+ "fast-uri": "^3.1.6",
"path-to-regexp": "^8.4.2",
- "@types/node": "26.2.0"
+ qs: "^6.16.0",
+ "ip-address": "^10.7.2",
+ "@types/node": "26.6.2"
},
trustedDependencies: []
};
@@ -466,7 +468,7 @@ function extractSemverFromOutput(output) {
return match?.[1] ?? null;
}
-// node_modules/.bun/[email protected]/node_modules/js-yaml/dist/js-yaml.mjs
+// node_modules/.bun/[email protected]/node_modules/js-yaml/dist/js-yaml.mjs
function defineScalarTag(tagName, options) {
return {
tagName,
@@ -1207,30 +1209,38 @@ function collectionTagName(state, event, defaultTagName) {
function isMappingTag(tag) {
return tag.nodeKind === "mapping";
}
+function chargeMergeWork(state) {
+ state.totalMergeKeys++;
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys)
+ throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
+}
function mergeKeys(state, frame, source, sourceTag) {
+ chargeMergeWork(state);
for (const sourceKey of sourceTag.keys(source)) {
- if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys)
- throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
+ chargeMergeWork(state);
if (frame.tag.has(frame.value, sourceKey))
continue;
const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
if (err)
throwError$1(state, err);
- (frame.overridable ??= /* @__PURE__ */ new Set).add(sourceKey);
+ frame.overridable ??= /* @__PURE__ */ new Set;
+ frame.overridable.add(sourceKey);
}
}
function mergeSource(state, frame, source, sourceTag) {
state.position = frame.keyPosition;
if (isMappingTag(sourceTag))
mergeKeys(state, frame, source, sourceTag);
- else if (sourceTag.nodeKind === "sequence" && Array.isArray(source))
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
+ if (source.length > 100)
+ throwError$1(state, "abnormal merge sequence size");
for (const element of source) {
const elementTag = state.nodeTags.get(element);
if (!elementTag)
throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
mergeKeys(state, frame, element, elementTag);
}
- else
+ } else
throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
}
function addMappingValue(state, frame, key, value, tag) {
@@ -1578,6 +1588,27 @@ function testDocumentSeparator(state, position = state.position) {
}
return false;
}
+function skipByteOrderMark(state) {
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
+ state.position++;
+ state.lineStart = state.position;
+ }
+}
+function testDocumentBoundary(state) {
+ if (state.position !== state.lineStart)
+ return false;
+ if (testDocumentSeparator(state))
+ return true;
+ if (state.input.charCodeAt(state.position) !== 65279)
+ return false;
+ const snapshot = snapshotState(state);
+ skipByteOrderMark(state);
+ skipSeparationSpace(state, true);
+ const ch = state.input.charCodeAt(state.position);
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
+ restoreState(state, snapshot);
+ return result;
+}
function skipUntilLineEnd(state) {
let ch = state.input.charCodeAt(state.position);
while (ch !== 0 && !isEol(ch))
@@ -1805,7 +1836,7 @@ function readBlockScalar(state, parentIndent, props) {
valueEnd = linePosition + column;
break;
}
- if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition))
+ if (testDocumentBoundary(state))
break;
if (!detectedIndent && contentIndent === -1 && isEol(first))
maxLeadingIndent = Math.max(maxLeadingIndent, column);
@@ -1864,7 +1895,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
const inFlow = nodeContext === CONTEXT_FLOW_IN;
let multiline = false;
while (ch !== 0) {
- if (state.position === state.lineStart && testDocumentSeparator(state))
+ if (testDocumentBoundary(state))
break;
if (ch === 58) {
const following = state.input.charCodeAt(state.position + 1);
@@ -2302,7 +2333,7 @@ function readDocument(state) {
if (documentEvent?.type === EVENT_ID.DOCUMENT)
documentEvent.explicitEnd = explicitEnd;
addPopEvent(state);
- if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state)))
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state))
throwError(state, "end of the stream or a document separator is expected");
}
function parseEvents(input, options) {
@@ -2325,9 +2356,8 @@ function parseEvents(input, options) {
const nullpos = input.indexOf("\x00");
if (nullpos !== -1)
YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
- if (state.input.charCodeAt(state.position) === 65279)
- state.position++;
while (state.position < state.length) {
+ skipByteOrderMark(state);
skipSeparationSpace(state, true);
if (state.position >= state.length)
break;
@@ -2359,6 +2389,85 @@ function load(input, options) {
return documents[0];
throw new YAMLException("expected a single document in the stream, but found more");
}
+function hasBit(mask, bit) {
+ return (mask & 1 << bit) !== 0;
+}
+function _preferredQuotedStyle(layout) {
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED))
+ return SCALAR_STYLE.SINGLE_QUOTED;
+ return SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function applyQuoteFlowKeysOption(layout) {
+ if (!layout.presenterOptions.quoteFlowKeys)
+ return;
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN)
+ return;
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function doubleQuoteForInvisibles(layout) {
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value))
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function doubleQuoteWhitespaceOnly(layout) {
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value))
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function applyForceQuotesOption(layout) {
+ if (!layout.presenterOptions.forceQuotes)
+ return;
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN)
+ return;
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName)
+ return;
+ layout.style = layout.node.value.includes(`
+`) ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
+}
+function tryLongOrMultilineAsBlock(layout) {
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey)
+ return;
+ const value = layout.node.value;
+ const multiline = value.indexOf(`
+`) !== -1;
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
+ if (multiline)
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+ return;
+ }
+ const w = layout.presenterOptions.lineWidth;
+ if (w === -1) {
+ if (multiline)
+ layout.style = SCALAR_STYLE.LITERAL_BLOCK;
+ return;
+ }
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
+ let position = 0;
+ let shouldFold = false;
+ while (position <= value.length) {
+ let lineEnd = value.length;
+ const nextLineBreak = value.indexOf(`
+`, position);
+ if (nextLineBreak !== -1)
+ lineEnd = nextLineBreak;
+ const line = value.slice(position, lineEnd);
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line))
+ shouldFold = true;
+ if (nextLineBreak === -1)
+ break;
+ position = nextLineBreak + 1;
+ }
+ if (shouldFold)
+ layout.style = SCALAR_STYLE.FOLDED_BLOCK;
+ else if (multiline)
+ layout.style = SCALAR_STYLE.LITERAL_BLOCK;
+}
+function quoteInvalidPlain(layout) {
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN))
+ layout.style = _preferredQuotedStyle(layout);
+}
+function fallbackToDoubleQuoted(layout) {
+ if (!hasBit(layout.allowedStylesMask, layout.style))
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
var NOT_RESOLVED, strTag, NULL_VALUES$1, nullCoreTag, nullJsonTag, NULL_VALUES, nullYaml11Tag, TRUE_VALUES$2, FALSE_VALUES$2, boolCoreTag, TRUE_VALUES$1, FALSE_VALUES$1, boolJsonTag, TRUE_VALUES, FALSE_VALUES, boolYaml11Tag, YAML_INTEGER_IMPLICIT_PATTERN$1, YAML_INTEGER_EXPLICIT_PATTERN$1, intCoreTag, YAML_INTEGER_IMPLICIT_PATTERN, YAML_INTEGER_EXPLICIT_PATTERN, intJsonTag, YAML_INTEGER_PATTERN, intYaml11Tag, YAML_FLOAT_PATTERN$1, YAML_FLOAT_SPECIAL_PATTERN$1, floatCoreTag, YAML_FLOAT_IMPLICIT_PATTERN, YAML_FLOAT_EXPLICIT_PATTERN, floatJsonTag, YAML_FLOAT_PATTERN, YAML_FLOAT_SPECIAL_PATTERN, floatYaml11Tag, mergeTag, BASE64_PATTERN, binaryTag, YAML_DATE_REGEXP, YAML_TIMESTAMP_REGEXP, timestampTag, seqTag, omapTag, pairsTag, mapTag, setTag, Schema = class Schema {
tags;
implicitScalarTags;
@@ -2469,9 +2578,9 @@ var NOT_RESOLVED, strTag, NULL_VALUES$1, nullCoreTag, nullJsonTag, NULL_VALUES,
flatTags = flatTags.concat(tag);
return new Schema([...this.tags, ...flatTags]);
}
-}, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, YAML11_SCHEMA, DUMP_SCHEMA, realMapTag, legacyMapTag, DEFAULT_SNIPPET_OPTIONS, YAMLException, EVENT_ID, SCALAR_STYLE, COLLECTION_STYLE, CHOMPING_MODE, NO_RANGE$3 = -1, simpleEscapeCheck, simpleEscapeMap, DEFAULT_TAG_HANDLERS, NO_RANGE$2 = -1, MERGE_TAG_NAME = "tag:yaml.org,2002:merge", DEFAULT_CONSTRUCTOR_OPTIONS, NO_RANGE$1 = -1, HAS_OWN, CONTEXT_FLOW_IN = 1, CONTEXT_FLOW_OUT = 2, CONTEXT_BLOCK_IN = 3, CONTEXT_BLOCK_OUT = 4, PATTERN_NON_PRINTABLE, PATTERN_FLOW_INDICATORS, PATTERN_TAG_HANDLE, NS_URI_CHAR, NS_TAG_CHAR, PATTERN_TAG_URI, PATTERN_TAG_SUFFIX, PATTERN_TAG_PREFIX, DEFAULT_PARSER_OPTIONS, DEFAULT_LOAD_OPTIONS, INVALID, VISIT_BREAK, VISIT_SKIP, ESCAPE_SEQUENCES, DEFAULT_PRESENTER_OPTIONS, DEFAULT_DUMP_OPTIONS, EVENT_DOCUMENT, EVENT_SEQUENCE, EVENT_MAPPING, EVENT_SCALAR, EVENT_ALIAS, EVENT_POP, SCALAR_STYLE_PLAIN, SCALAR_STYLE_SINGLE_QUOTED, SCALAR_STYLE_DOUBLE_QUOTED, SCALAR_STYLE_LITERAL_BLOCK, SCALAR_STYLE_FOLDED_BLOCK, COLLECTION_STYLE_BLOCK, COLLECTION_STYLE_FLOW, CHOMPING_CLIP, CHOMPING_STRIP, CHOMPING_KEEP;
+}, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, YAML11_SCHEMA, DUMP_SCHEMA, realMapTag, legacyMapTag, DEFAULT_SNIPPET_OPTIONS, YAMLException, EVENT_ID, SCALAR_STYLE, COLLECTION_STYLE, CHOMPING_MODE, NO_RANGE$3 = -1, simpleEscapeCheck, simpleEscapeMap, DEFAULT_TAG_HANDLERS, NO_RANGE$2 = -1, MERGE_TAG_NAME = "tag:yaml.org,2002:merge", DEFAULT_CONSTRUCTOR_OPTIONS, NO_RANGE$1 = -1, HAS_OWN, CONTEXT_FLOW_IN = 1, CONTEXT_FLOW_OUT = 2, CONTEXT_BLOCK_IN = 3, CONTEXT_BLOCK_OUT = 4, PATTERN_NON_PRINTABLE, PATTERN_FLOW_INDICATORS, PATTERN_TAG_HANDLE, NS_URI_CHAR, NS_TAG_CHAR, PATTERN_TAG_URI, PATTERN_TAG_SUFFIX, PATTERN_TAG_PREFIX, DEFAULT_PARSER_OPTIONS, DEFAULT_LOAD_OPTIONS, INVALID, VISIT_BREAK, VISIT_SKIP, DEFAULT_SCALAR_STYLE_RULES, SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]", SRC_B_CHAR = "[\\n\\r]", SRC_C_BYTE_ORDER_MARK = "\\uFEFF", SRC_S_WHITE = "[ \\t]", SRC_NB_CHAR, SRC_NS_CHAR, SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]", SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]", SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]", SRC_NS_PLAIN_SAFE_FLOW_OUT, SRC_NS_PLAIN_SAFE_FLOW_IN, SRC_NS_PLAIN_FIRST_FLOW_OUT, SRC_NS_PLAIN_FIRST_FLOW_IN, SRC_NS_PLAIN_CHAR_FLOW_OUT, SRC_NS_PLAIN_CHAR_FLOW_IN, SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT, SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN, SRC_NS_PLAIN_ONE_LINE_FLOW_OUT, SRC_NS_PLAIN_ONE_LINE_FLOW_IN, SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY, SRC_NS_PLAIN_ONE_LINE_FLOW_KEY, SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT, SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN, SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT, SRC_NS_PLAIN_MULTI_LINE_FLOW_IN, NS_PLAIN_FLOW_OUT, NS_PLAIN_FLOW_IN, NS_PLAIN_BLOCK_KEY, NS_PLAIN_FLOW_KEY, NB_SINGLE_ONE_LINE, NB_SINGLE_MULTI_LINE, BLOCK_SCALAR_CONTENT, DEFAULT_PRESENTER_OPTIONS, DEFAULT_DUMP_OPTIONS, EVENT_DOCUMENT, EVENT_SEQUENCE, EVENT_MAPPING, EVENT_SCALAR, EVENT_ALIAS, EVENT_POP, SCALAR_STYLE_PLAIN, SCALAR_STYLE_SINGLE_QUOTED, SCALAR_STYLE_DOUBLE_QUOTED, SCALAR_STYLE_LITERAL_BLOCK, SCALAR_STYLE_FOLDED_BLOCK, COLLECTION_STYLE_BLOCK, COLLECTION_STYLE_FLOW, CHOMPING_CLIP, CHOMPING_STRIP, CHOMPING_KEEP;
var init_js_yaml = __esm(() => {
- /*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT */
+ /*! js-yaml 5.4.2 https://github.com/nodeca/js-yaml @license MIT */
NOT_RESOLVED = Symbol("NOT_RESOLVED");
strTag = defineScalarTag("tag:yaml.org,2002:str", {
resolve: (source) => source,
@@ -3042,27 +3151,44 @@ var init_js_yaml = __esm(() => {
INVALID = Symbol("INVALID");
VISIT_BREAK = Symbol("visit:break");
VISIT_SKIP = Symbol("visit:skip");
- ESCAPE_SEQUENCES = {};
- ESCAPE_SEQUENCES[0] = "\\0";
- ESCAPE_SEQUENCES[7] = "\\a";
- ESCAPE_SEQUENCES[8] = "\\b";
- ESCAPE_SEQUENCES[9] = "\\t";
- ESCAPE_SEQUENCES[10] = "\\n";
- ESCAPE_SEQUENCES[11] = "\\v";
- ESCAPE_SEQUENCES[12] = "\\f";
- ESCAPE_SEQUENCES[13] = "\\r";
- ESCAPE_SEQUENCES[27] = "\\e";
- ESCAPE_SEQUENCES[34] = "\\\"";
- ESCAPE_SEQUENCES[92] = "\\\\";
- ESCAPE_SEQUENCES[133] = "\\N";
- ESCAPE_SEQUENCES[160] = "\\_";
- ESCAPE_SEQUENCES[8232] = "\\L";
- ESCAPE_SEQUENCES[8233] = "\\P";
+ DEFAULT_SCALAR_STYLE_RULES = {
+ applyQuoteFlowKeysOption,
+ doubleQuoteForInvisibles,
+ doubleQuoteWhitespaceOnly,
+ applyForceQuotesOption,
+ tryLongOrMultilineAsBlock,
+ quoteInvalidPlain,
+ fallbackToDoubleQuoted
+ };
+ SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
+ SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
+ SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
+ SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
+ SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
+ SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
+ SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
+ SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
+ SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
+ SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
+ SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
+ SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
+ SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
+ SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
+ SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
+ SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
+ SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
+ SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
+ NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
+ NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
+ NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
+ NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
+ NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
+ NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
+ BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
DEFAULT_PRESENTER_OPTIONS = {
indent: 2,
seqNoIndent: false,
seqInlineFirst: true,
- sortKeys: false,
lineWidth: 80,
flowBracketPadding: false,
flowSkipCommaSpace: false,
@@ -3070,6 +3196,7 @@ var init_js_yaml = __esm(() => {
quoteFlowKeys: false,
quoteStyle: "single",
forceQuotes: false,
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
tagBeforeAnchor: false
};
DEFAULT_DUMP_OPTIONS = {
@@ -3078,6 +3205,7 @@ var init_js_yaml = __esm(() => {
skipInvalid: false,
noRefs: false,
flowLevel: -1,
+ sortKeys: false,
transform: () => {}
};
EVENT_DOCUMENT = EVENT_ID.DOCUMENT;
@@ -64671,10 +64799,10 @@ var init_tmux = __esm(() => {
init_runner2();
init_tmux_utils2();
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/types.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/types.gen.js
var init_types_gen = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/serverSentEvents.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/serverSentEvents.gen.js
var createSseClient = ({ onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
let lastEventId;
const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
@@ -64783,7 +64911,7 @@ var createSseClient = ({ onSseError, onSseEvent, responseTransformer, responseVa
return { stream };
};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/auth.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/auth.gen.js
var getAuthToken = async (auth, callback) => {
const token = typeof callback === "function" ? await callback(auth) : callback;
if (!token) {
@@ -64798,7 +64926,7 @@ var getAuthToken = async (auth, callback) => {
return token;
};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/bodySerializer.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/bodySerializer.gen.js
var jsonBodySerializer;
var init_bodySerializer_gen = __esm(() => {
jsonBodySerializer = {
@@ -64806,7 +64934,7 @@ var init_bodySerializer_gen = __esm(() => {
};
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/pathSerializer.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/pathSerializer.gen.js
var separatorArrayExplode = (style) => {
switch (style) {
case "label":
@@ -64904,7 +65032,7 @@ var separatorArrayExplode = (style) => {
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/utils.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/utils.gen.js
var PATH_PARAM_RE, defaultPathSerializer = ({ path, url: _url }) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
@@ -64973,7 +65101,7 @@ var init_utils_gen = __esm(() => {
PATH_PARAM_RE = /\{[^{}]+\}/g;
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/utils.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/utils.gen.js
class Interceptors {
_fns;
constructor() {
@@ -65176,7 +65304,7 @@ var init_utils_gen2 = __esm(() => {
};
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/client.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/client.gen.js
var createClient = (config = {}) => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = () => ({ ..._config });
@@ -65327,7 +65455,7 @@ var init_client_gen = __esm(() => {
init_utils_gen2();
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/params.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/params.gen.js
var extraPrefixesMap, extraPrefixes;
var init_params_gen = __esm(() => {
extraPrefixesMap = {
@@ -65339,7 +65467,7 @@ var init_params_gen = __esm(() => {
extraPrefixes = Object.entries(extraPrefixesMap);
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/index.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/index.js
var init_client = __esm(() => {
init_bodySerializer_gen();
init_params_gen();
@@ -65347,7 +65475,7 @@ var init_client = __esm(() => {
init_utils_gen2();
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client.gen.js
var client;
var init_client_gen2 = __esm(() => {
init_client();
@@ -65356,7 +65484,7 @@ var init_client_gen2 = __esm(() => {
}));
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/sdk.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/sdk.gen.js
class _HeyApiClient {
_client = client;
constructor(args) {
@@ -66007,7 +66135,7 @@ var init_sdk_gen = __esm(() => {
};
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/error-interceptor.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/error-interceptor.js
function wrapClientError(error, response, request, opts) {
if (!opts?.throwOnError)
return error;
@@ -66034,7 +66162,7 @@ function describe(request, response) {
return `${method} ${url}${status ? " → " + status : ""}${statusText ? " " + statusText : ""}`;
}
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/client.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/client.js
function pick2(value, fallback) {
if (!value)
return;
@@ -66544,7 +66672,7 @@ var require_cross_spawn = __commonJS(function(exports, module) {
module.exports._enoent = enoent;
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/process.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/process.js
import { spawnSync as spawnSync2 } from "node:child_process";
function stop(proc) {
if (proc.exitCode !== null || proc.signalCode !== null)
@@ -66578,7 +66706,7 @@ function bindAbort(proc, signal, onAbort) {
}
var init_process = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/server.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/server.js
async function createOpencodeServer(options) {
options = Object.assign({
hostname: "127.0.0.1",
@@ -66661,7 +66789,7 @@ var init_server = __esm(() => {
import_cross_spawn = __toESM(require_cross_spawn(), 1);
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/index.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/index.js
async function createOpencode(options) {
const server2 = await createOpencodeServer({
...options
@@ -67603,83 +67731,7 @@ var init_shared = __esm(() => {
init_replace_tool_args();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/core.js
-function $constructor(name, initializer, params) {
- function init(inst, def) {
- if (!inst._zod) {
- Object.defineProperty(inst, "_zod", {
- value: {
- def,
- constr: _,
- traits: new Set
- },
- enumerable: false
- });
- }
- if (inst._zod.traits.has(name)) {
- return;
- }
- inst._zod.traits.add(name);
- initializer(inst, def);
- const proto = _.prototype;
- const keys = Object.keys(proto);
- for (let i = 0;i < keys.length; i++) {
- const k = keys[i];
- if (!(k in inst)) {
- inst[k] = proto[k].bind(inst);
- }
- }
- }
- const Parent = params?.Parent ?? Object;
-
- class Definition extends Parent {
- }
- Object.defineProperty(Definition, "name", { value: name });
- function _(def) {
- var _a;
- const inst = params?.Parent ? new Definition : this;
- init(inst, def);
- (_a = inst._zod).deferred ?? (_a.deferred = []);
- for (const fn of inst._zod.deferred) {
- fn();
- }
- return inst;
- }
- Object.defineProperty(_, "init", { value: init });
- Object.defineProperty(_, Symbol.hasInstance, {
- value: (inst) => {
- if (params?.Parent && inst instanceof params.Parent)
- return true;
- return inst?._zod?.traits?.has(name);
- }
- });
- Object.defineProperty(_, "name", { value: name });
- return _;
-}
-function config(newConfig) {
- if (newConfig)
- Object.assign(globalConfig, newConfig);
- return globalConfig;
-}
-var _a, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig;
-var init_core = __esm(() => {
- $brand = Symbol("zod_brand");
- $ZodAsyncError = class $ZodAsyncError extends Error {
- constructor() {
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
- }
- };
- $ZodEncodeError = class $ZodEncodeError extends Error {
- constructor(name) {
- super(`Encountered unidirectional transform during encode: ${name}`);
- this.name = "ZodEncodeError";
- }
- };
- (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
- globalConfig = globalThis.__zod_globalConfig;
-});
-
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/util.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
@@ -67693,18 +67745,23 @@ function jsonStringifyReplacer(_, value) {
return value.toString();
return value;
}
-function cached(getter) {
- const set = false;
- return {
- get value() {
- if (!set) {
- const value = getter();
- Object.defineProperty(this, "value", { value });
- return value;
- }
- throw new Error("cached value already set");
+
+class Cached {
+ constructor(getter) {
+ this._getter = getter;
+ this._value = undefined;
+ }
+ get value() {
+ const getter = this._getter;
+ if (getter !== undefined) {
+ this._value = getter();
+ this._getter = undefined;
}
- };
+ return this._value;
+ }
+}
+function cached(getter) {
+ return new Cached(getter);
}
function nullish(input) {
return input === null || input === undefined;
@@ -67717,32 +67774,11 @@ function cleanRegex(source) {
function floatSafeRemainder(val, step) {
const ratio = val / step;
const roundedRatio = Math.round(ratio);
- const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance)
return 0;
return ratio - roundedRatio;
}
-function defineLazy(object, key, getter) {
- let value = undefined;
- Object.defineProperty(object, key, {
- get() {
- if (value === EVALUATING) {
- return;
- }
- if (value === undefined) {
- value = EVALUATING;
- value = getter();
- }
- return value;
- },
- set(v) {
- Object.defineProperty(object, key, {
- value: v
- });
- },
- configurable: true
- });
-}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
@@ -67751,6 +67787,56 @@ function assignProp(target, prop, value) {
configurable: true
});
}
+function rawShape(def) {
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
+ return desc?.get ? desc.get.raw : desc?.value;
+}
+function sourceShape(schema) {
+ return rawShape(schema._zod.def) ?? schema._zod.def.shape;
+}
+function deferProp(target, key, getter) {
+ Object.defineProperty(target, key, {
+ get() {
+ const value = getter();
+ assignProp(this, key, value);
+ return value;
+ },
+ enumerable: true,
+ configurable: true
+ });
+}
+function putProp(target, key, value) {
+ if (key in target)
+ assignProp(target, key, value);
+ else
+ target[key] = value;
+}
+function mirrorShape(target, source, keys, wrap) {
+ const raw = sourceShape(source);
+ for (const key of keys) {
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
+ if (!desc.enumerable)
+ continue;
+ if (desc.get) {
+ deferProp(target, key, () => {
+ const value = source._zod.def.shape[key];
+ return wrap ? wrap(value, key) : value;
+ });
+ } else
+ putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
+ }
+}
+function mirrorProps(target, source) {
+ for (const key of Reflect.ownKeys(source)) {
+ const desc = Object.getOwnPropertyDescriptor(source, key);
+ if (!desc.enumerable)
+ continue;
+ if (desc.get)
+ deferProp(target, key, () => source[key]);
+ else
+ putProp(target, key, desc.value);
+ }
+}
function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
@@ -67829,7 +67915,7 @@ function stringifyPrimitive(value) {
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
+ return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional";
});
}
function pick3(schema, mask) {
@@ -67839,23 +67925,21 @@ function pick3(schema, mask) {
if (hasChecks) {
throw new Error(".pick() cannot be used on object schemas containing refinements");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const newShape = {};
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- newShape[key] = currDef.shape[key];
- }
- assignProp(this, "shape", newShape);
- return newShape;
- },
- checks: []
- });
- return clone(schema, def);
+ const newShape = {};
+ mirrorShape(newShape, schema, maskedKeys(schema, mask));
+ return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
+}
+function maskedKeys(schema, mask) {
+ const raw = sourceShape(schema);
+ const keys = [];
+ for (const key of Reflect.ownKeys(mask)) {
+ if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {
+ throw new Error(`Unrecognized key: "${String(key)}"`);
+ }
+ if (mask[key])
+ keys.push(key);
+ }
+ return keys;
}
function omit(schema, mask) {
const currDef = schema._zod.def;
@@ -67864,23 +67948,10 @@ function omit(schema, mask) {
if (hasChecks) {
throw new Error(".omit() cannot be used on object schemas containing refinements");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const newShape = { ...schema._zod.def.shape };
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- delete newShape[key];
- }
- assignProp(this, "shape", newShape);
- return newShape;
- },
- checks: []
- });
- return clone(schema, def);
+ const omitted = new Set(maskedKeys(schema, mask));
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));
+ return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
}
function extend(schema, shape) {
if (!isPlainObject3(shape)) {
@@ -67889,45 +67960,39 @@ function extend(schema, shape) {
const checks = schema._zod.def.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
- const existingShape = schema._zod.def.shape;
- for (const key in shape) {
+ const existingShape = sourceShape(schema);
+ for (const key of Reflect.ownKeys(shape)) {
if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
}
}
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- }
- });
- return clone(schema, def);
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
+}
+function extended(schema, shape) {
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
+ mirrorProps(newShape, shape);
+ return newShape;
}
function safeExtend(schema, shape) {
if (!isPlainObject3(shape)) {
throw new Error("Invalid input to safeExtend: expected a plain object");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- }
- });
- return clone(schema, def);
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
}
function merge(a, b) {
+ if (!b?._zod?.def) {
+ throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
+ }
if (a._zod.def.checks?.length) {
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
}
+ const newShape = {};
+ mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));
+ mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));
const def = mergeDefs(a._zod.def, {
- get shape() {
- const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
- assignProp(this, "shape", _shape);
- return _shape;
- },
+ shape: newShape,
get catchall() {
return b._zod.def.catchall;
},
@@ -67935,74 +68000,23 @@ function merge(a, b) {
});
return clone(a, def);
}
-function partial(Class, schema, mask) {
+function partial(Class, schema, mask, name = "partial") {
const currDef = schema._zod.def;
const checks = currDef.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
- throw new Error(".partial() cannot be used on object schemas containing refinements");
- }
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in oldShape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- } else {
- for (const key in oldShape) {
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- }
- assignProp(this, "shape", shape);
- return shape;
- },
- checks: []
- });
- return clone(schema, def);
+ throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
+ }
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && ((value, key) => selected && !selected.has(key) ? value : new Class({ type: "optional", innerType: value })));
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));
}
function required(Class, schema, mask) {
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- } else {
- for (const key in oldShape) {
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- }
- assignProp(this, "shape", shape);
- return shape;
- }
- });
- return clone(schema, def);
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => selected && !selected.has(key) ? value : new Class({ type: "nonoptional", innerType: value }));
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));
}
function aborted(x, startIndex = 0) {
if (x.aborted === true)
@@ -68035,15 +68049,48 @@ function prefixIssues(path, issues) {
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
+function attachSchema(issues, start, inst) {
+ var _a;
+ for (let i = start;i < issues.length; i++) {
+ (_a = issues[i]).schema ?? (_a.schema = inst);
+ }
+}
function finalizeIssue(iss, ctx, config) {
- const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
- const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
- rest.path ?? (rest.path = []);
- rest.message = message;
+ var _a;
+ const traits = iss.inst?._zod?.traits;
+ if (traits?.has("$ZodType")) {
+ if (traits.has("$ZodCheck"))
+ (_a = iss).schema ?? (_a.schema = iss.inst);
+ else
+ iss.schema = iss.inst;
+ }
+ const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
+ const full = {};
+ for (const k of Object.keys(iss)) {
+ if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__")
+ continue;
+ full[k] = iss[k];
+ }
+ full.path ?? (full.path = []);
+ full.message = message;
if (ctx?.reportInput) {
- rest.input = _input;
+ full.input = iss.input;
}
- return rest;
+ return full;
+}
+function codePointLength(str) {
+ const units = str.length;
+ if (!highSurrogate.test(str))
+ return units;
+ let count = units;
+ for (let i = 0;i < units - 1; i++) {
+ if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
+ count--;
+ i++;
+ }
+ }
+ return count;
}
function getLengthableOrigin(input) {
if (Array.isArray(input))
@@ -68085,10 +68132,111 @@ function issue(...args) {
}
return { ...iss };
}
-var EVALUATING, captureStackTrace, allowsEval, propertyKeyTypes, NUMBER_FORMAT_RANGES;
+function members(proto, table) {
+ for (const key in table) {
+ const desc = Object.getOwnPropertyDescriptor(table, key);
+ if (desc.get)
+ Object.defineProperty(proto, key, { ...desc, enumerable: false });
+ else
+ defineBound(proto, key, desc.value);
+ }
+}
+function own(inst, key, value, enumerable = true) {
+ Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });
+ return value;
+}
+function hide(inst, key, value) {
+ return own(inst, key, value, false);
+}
+function derived(computes, table) {
+ for (const key in computes) {
+ const compute = computes[key];
+ Object.defineProperty(table, key, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ return own(this, key, compute(this));
+ },
+ set(value) {
+ own(this, key, value);
+ }
+ });
+ }
+ return table;
+}
+function defineBound(proto, key, fn) {
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ return this == null ? fn : own(this, key, fn.bind(this));
+ },
+ set(value) {
+ own(this, key, value);
+ }
+ });
+}
+function claim(inst, sentinel) {
+ const proto = Object.getPrototypeOf(inst);
+ return sentinel in proto ? undefined : proto;
+}
+function defineLazyInternal(inst, key, compute) {
+ const proto = Object.getPrototypeOf(inst._zod);
+ if (key in proto && installing !== inst._zod) {
+ installing = undefined;
+ return;
+ }
+ installing = inst._zod;
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ Object.defineProperty(this, key, breaker);
+ const outer = broke;
+ broke = false;
+ try {
+ const value = compute(this);
+ if (broke)
+ delete this[key];
+ else
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
+ broke = broke || outer;
+ return value;
+ } catch (err) {
+ delete this[key];
+ broke = broke || outer;
+ throw err;
+ }
+ },
+ set(value) {
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
+ }
+ });
+}
+function installLazyProp(inst, key, make, enumerable) {
+ const proto = claim(inst, key);
+ if (!proto)
+ return;
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ const desc = { configurable: true, writable: true, enumerable, value: undefined };
+ Object.defineProperty(this, key, desc);
+ desc.value = make(this);
+ Object.defineProperty(this, key, desc);
+ return desc.value;
+ },
+ set(value) {
+ Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });
+ }
+ });
+}
+function constantCatch(value) {
+ const fn = () => value;
+ fn[CONSTANT_CATCH] = true;
+ return fn;
+}
+var captureStackTrace, allowsEval, propertyKeyTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, highSurrogate, installing, broke = false, breaker, CONSTANT_CATCH = "~constantCatch";
var init_util = __esm(() => {
init_core();
- EVALUATING = /* @__PURE__ */ Symbol("evaluating");
captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
allowsEval = /* @__PURE__ */ cached(() => {
if (globalConfig.jitless) {
@@ -68106,23 +68254,173 @@ var init_util = __esm(() => {
}
});
propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
- NUMBER_FORMAT_RANGES = {
+ NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
+ }))();
+ BIGINT_FORMAT_RANGES = {
+ int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
+ uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
+ };
+ highSurrogate = /[\uD800-\uDBFF]/;
+ breaker = {
+ configurable: true,
+ get() {
+ broke = true;
+ return;
+ }
};
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/errors.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/core.js
+function newError(Definition) {
+ const E = _E;
+ if (E) {
+ const saved = E.stackTraceLimit;
+ if (typeof saved === "number") {
+ try {
+ E.stackTraceLimit = 0;
+ } catch {
+ _E = null;
+ return new Definition;
+ }
+ try {
+ return new Definition;
+ } finally {
+ E.stackTraceLimit = saved;
+ }
+ }
+ }
+ return new Definition;
+}
+function $constructor(name, initializer, proto, params) {
+ const zodProto = {};
+ function Internals(def) {
+ this.def = def;
+ this.constr = _;
+ this.traits = new Set;
+ }
+ Internals.prototype = zodProto;
+ const protoMembers = proto;
+ const initialized = protoMembers && new WeakSet;
+ function init(inst, def) {
+ if (!inst._zod) {
+ _zodDesc.value = new Internals(def);
+ try {
+ Object.defineProperty(inst, "_zod", _zodDesc);
+ } finally {
+ _zodDesc.value = undefined;
+ }
+ } else if (inst._zod.traits.has(name)) {
+ return;
+ }
+ inst._zod.traits.add(name);
+ initializer(inst, def);
+ if (initialized) {
+ const own = Object.getPrototypeOf(inst);
+ const ctorProto = inst._zod.constr.prototype;
+ let up = own;
+ while (up && up !== ctorProto)
+ up = Object.getPrototypeOf(up);
+ const target = up ?? own;
+ if (!initialized.has(target)) {
+ initialized.add(target);
+ members(target, protoMembers);
+ }
+ }
+ const proto = _.prototype;
+ for (const k in proto) {
+ if (!Object.prototype.hasOwnProperty.call(proto, k))
+ continue;
+ if (!(k in inst)) {
+ inst[k] = proto[k].bind(inst);
+ }
+ }
+ }
+ const Parent = params?.Parent ?? Object;
+
+ class Definition extends Parent {
+ }
+ Object.defineProperty(Definition, "name", { value: name });
+ function _(def) {
+ const inst = params?.Parent ? newError(Definition) : this;
+ init(inst, def);
+ const deferred = inst._zod.deferred;
+ if (deferred) {
+ for (const fn of deferred) {
+ fn();
+ }
+ inst._zod.deferred = undefined;
+ }
+ const pp = globalThis.__zod_globalConfig?.postProcessor;
+ if (pp)
+ pp(inst);
+ return inst;
+ }
+ Object.defineProperty(_, "init", { value: init });
+ Object.defineProperty(_, Symbol.hasInstance, {
+ value: (inst) => {
+ if (params?.Parent && inst instanceof params.Parent)
+ return true;
+ return inst?._zod?.traits?.has(name);
+ }
+ });
+ Object.defineProperty(_, "name", { value: name });
+ return _;
+}
+function config(newConfig) {
+ if (newConfig)
+ Object.assign(globalConfig, newConfig);
+ return globalConfig;
+}
+var _a, _zodDesc, _E, $ZodAsyncError, $ZodEncodeError, globalConfig;
+var init_core = __esm(() => {
+ init_util();
+ _zodDesc = { value: undefined, enumerable: false };
+ _E = "captureStackTrace" in Error ? Error : null;
+ $ZodAsyncError = class $ZodAsyncError extends Error {
+ constructor() {
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
+ }
+ };
+ $ZodEncodeError = class $ZodEncodeError extends Error {
+ constructor(name) {
+ super(`Encountered unidirectional transform during encode: ${name}`);
+ this.name = "ZodEncodeError";
+ }
+ };
+ (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
+ globalConfig = globalThis.__zod_globalConfig;
+});
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/errors.js
+function _getMessage() {
+ const internals = this._zod;
+ internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
+ return internals.message;
+}
+function _setMessage(value) {
+ this._zod.message = value;
+}
+function node(obj, key, make) {
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) {
+ if (key === "__proto__") {
+ Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
+ } else {
+ obj[key] = make();
+ }
+ }
+ return obj[key];
+}
function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) {
if (sub.path.length > 0) {
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
- fieldErrors[sub.path[0]].push(mapper(sub));
+ node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
@@ -68149,13 +68447,25 @@ function formatError2(error, mapper = (issue) => issue.message) {
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- } else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue));
+ if (el === "_errors") {
+ if (terminal)
+ curr._errors.push(mapper(issue));
+ i++;
+ continue;
+ }
+ if (!Object.prototype.hasOwnProperty.call(curr, el)) {
+ Object.defineProperty(curr, el, {
+ value: { _errors: [] },
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ const node = curr[el];
+ if (terminal) {
+ node._errors.push(mapper(issue));
}
- curr = curr[el];
+ curr = node;
i++;
}
}
@@ -68165,82 +68475,167 @@ function formatError2(error, mapper = (issue) => issue.message) {
processError(error);
return fieldErrors;
}
-var initializer = (inst, def) => {
+var _messageDesc, _issuesDesc, _installedToString, initializer = (inst, def) => {
inst.name = "$ZodError";
- Object.defineProperty(inst, "_zod", {
- value: inst._zod,
- enumerable: false
- });
- Object.defineProperty(inst, "issues", {
- value: def,
- enumerable: false
- });
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
- Object.defineProperty(inst, "toString", {
- value: () => inst.message,
- enumerable: false
- });
+ _issuesDesc.value = def;
+ Object.defineProperty(inst, "issues", _issuesDesc);
+ _issuesDesc.value = undefined;
+ Object.defineProperty(inst, "message", _messageDesc);
+ const proto = Object.getPrototypeOf(inst);
+ if (!_installedToString.has(proto)) {
+ _installedToString.add(proto);
+ Object.defineProperty(proto, "toString", {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const value = () => this.message;
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
+ return value;
+ },
+ set(value) {
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
+ }
+ });
+ }
}, $ZodError, $ZodRealError;
var init_errors = __esm(() => {
init_core();
init_util();
+ _messageDesc = {
+ get: _getMessage,
+ set: _setMessage,
+ enumerable: true,
+ configurable: true
+ };
+ _issuesDesc = { value: undefined, enumerable: false };
+ _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
$ZodError = $constructor("$ZodError", initializer);
- $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
+ $ZodRealError = $constructor("$ZodError", initializer, undefined, {
+ Parent: Error
+ });
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/parse.js
-var _parse = (_Err) => (schema, value, _ctx, _params) => {
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
- const result = schema._zod.run({ value, issues: [] }, ctx);
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/parse.js
+function finalizeParams(callee, params) {
+ return { callee: params?.callee ?? callee, Err: params?.Err };
+}
+function failure(Err, issues, ctx) {
+ let error;
+ return {
+ success: false,
+ get error() {
+ if (!error) {
+ error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ issues = undefined;
+ ctx = undefined;
+ }
+ return error;
+ },
+ set error(e) {
+ error = e;
+ issues = undefined;
+ ctx = undefined;
+ }
+ };
+}
+function validateFallback(schema, value, _ctx) {
+ const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true };
+ const fallbackRun = schema._zod.bag.fallbackRun;
+ let result;
+ if (fallbackRun) {
+ ctx[COMPILE_FALLBACK] = true;
+ result = fallbackRun({ value, issues: [] }, ctx);
+ } else {
+ result = schema._zod.run({ value, issues: [] }, ctx);
+ }
if (result instanceof Promise) {
throw new $ZodAsyncError;
}
- if (result.issues.length) {
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, _params?.callee);
- throw e;
- }
- return result.value;
-}, _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
- const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
- let result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise)
- result = await result;
- if (result.issues.length) {
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, params?.callee);
- throw e;
- }
- return result.value;
+ return result.issues.length === 0;
+}
+var _parse = (_Err) => {
+ const fn = (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
+ const result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ throw new $ZodAsyncError;
+ }
+ if (result.issues.length) {
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, _params?.callee ?? fn);
+ throw e;
+ }
+ return result.value;
+ };
+ return fn;
+}, _parseAsync = (_Err) => {
+ const fn = async (schema, value, _ctx, params) => {
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ if (result.issues.length) {
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, params?.callee ?? fn);
+ throw e;
+ }
+ return result.value;
+ };
+ return fn;
}, _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new $ZodAsyncError;
}
- return result.issues.length ? {
- success: false,
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
-}, safeParse, _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
+ return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
+}, _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
- return result.issues.length ? {
- success: false,
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
-}, safeParseAsync, _encode = (_Err) => (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
- return _parse(_Err)(schema, value, ctx);
-}, _decode = (_Err) => (schema, value, _ctx) => {
- return _parse(_Err)(schema, value, _ctx);
-}, _encodeAsync = (_Err) => async (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
- return _parseAsync(_Err)(schema, value, ctx);
-}, _decodeAsync = (_Err) => async (schema, value, _ctx) => {
- return _parseAsync(_Err)(schema, value, _ctx);
+ return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
+}, COMPILE_INVALID, COMPILE_FALLBACK, validate = (schema, value, _ctx) => {
+ const validator = schema._zod.bag.validator;
+ if (validator !== undefined) {
+ if (validator(value) !== COMPILE_INVALID)
+ return true;
+ if (validator.definite === true && _ctx === undefined)
+ return false;
+ }
+ return validateFallback(schema, value, _ctx);
+}, validateAsync = async (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ return result.issues.length === 0;
+}, _encode = (_Err) => {
+ const parse = _parse(_Err);
+ const fn = (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return parse(schema, value, ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+}, _decode = (_Err) => {
+ const parse = _parse(_Err);
+ const fn = (schema, value, _ctx, _params) => {
+ return parse(schema, value, _ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+}, _encodeAsync = (_Err) => {
+ const parseAsync = _parseAsync(_Err);
+ const fn = async (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return await parseAsync(schema, value, ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+}, _decodeAsync = (_Err) => {
+ const parseAsync = _parseAsync(_Err);
+ const fn = async (schema, value, _ctx, _params) => {
+ return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
+ };
+ return fn;
}, _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _safeParse(_Err)(schema, value, ctx);
@@ -68254,61 +68649,62 @@ var _parse = (_Err) => (schema, value, _ctx, _params) => {
};
var init_parse = __esm(() => {
init_core();
- init_errors();
init_util();
- safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
- safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
+ COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
+ COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/regexes.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/regexes.js
+function nanoidOfLength(length) {
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
+}
function emoji() {
return new RegExp(_emoji, "u");
}
+function anchor(source) {
+ return new RegExp(`^${source}$`);
+}
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
- const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
+ const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
return regex;
}
function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
- const time = timeSource({ precision: args.precision });
const opts = ["Z"];
- if (args.local)
- opts.push("");
if (args.offset)
opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
- const timeRegex = `${time}(?:${opts.join("|")})`;
+ const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid = (version) => {
if (!version)
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)$/;
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})$`);
-}, email, _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, 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])))`, date, string = (params) => {
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
- return new RegExp(`^${regex}$`);
-}, integer, number, boolean, lowercase, uppercase;
+}, email, _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, 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])))`, date, anyString, integer, number, boolean, lowercase, uppercase;
var init_regexes = __esm(() => {
cuid = /^[cC][0-9a-z]{6,}$/;
cuid2 = /^[0-9a-z]+$/;
- ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
+ ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
xid = /^[0-9a-vA-V]{20}$/;
ksuid = /^[A-Za-z0-9]{27}$/;
nanoid = /^[a-zA-Z0-9_-]{21}$/;
duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
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})$/;
- email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
+ email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
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])$/;
ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
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])$/;
- 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])$/;
+ cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
- base64url = /^[A-Za-z0-9_-]*$/;
+ base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
httpProtocol = /^https?$/;
e164 = /^\+[1-9]\d{6,14}$/;
- date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
+ date = /* @__PURE__ */ anchor(dateSource);
+ anyString = /^[\s\S]{0,}$/;
integer = /^-?\d+$/;
number = /^-?\d+(?:\.\d+)?$/;
boolean = /^(?:true|false)$/i;
@@ -68316,8 +68712,11 @@ var init_regexes = __esm(() => {
uppercase = /^[^a-z]*$/;
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/checks.js
-var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite;
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/checks.js
+var $ZodCheck, _whenHasLength = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.length !== undefined;
+}, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite;
var init_checks = __esm(() => {
init_core();
init_regexes();
@@ -68336,22 +68735,12 @@ var init_checks = __esm(() => {
$ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
- if (def.value < curr) {
- if (def.inclusive)
- bag.maximum = def.value;
- else
- bag.exclusiveMaximum = def.value;
- }
- });
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
- origin,
+ origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
@@ -68364,22 +68753,12 @@ var init_checks = __esm(() => {
$ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
- if (def.value > curr) {
- if (def.inclusive)
- bag.minimum = def.value;
- else
- bag.exclusiveMinimum = def.value;
- }
- });
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
- origin,
+ origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
@@ -68391,14 +68770,10 @@ var init_checks = __esm(() => {
});
$ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
- inst._zod.onattach.push((inst) => {
- var _a;
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
- });
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
- const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
+ const isMultiple = typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
@@ -68417,14 +68792,6 @@ var init_checks = __esm(() => {
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.format = def.format;
- bag.minimum = minimum;
- bag.maximum = maximum;
- if (isInt)
- bag.pattern = integer;
- });
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
@@ -68493,18 +68860,11 @@ var init_checks = __esm(() => {
$ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
- if (def.maximum < curr)
- inst._zod.bag.maximum = def.maximum;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units;
if (length <= def.maximum)
return;
const origin = getLengthableOrigin(input);
@@ -68522,18 +68882,11 @@ var init_checks = __esm(() => {
$ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
- if (def.minimum > curr)
- inst._zod.bag.minimum = def.minimum;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units;
if (length >= def.minimum)
return;
const origin = getLengthableOrigin(input);
@@ -68551,19 +68904,11 @@ var init_checks = __esm(() => {
$ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.minimum = def.length;
- bag.maximum = def.length;
- bag.length = def.length;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
if (length === def.length)
return;
const origin = getLengthableOrigin(input);
@@ -68582,14 +68927,6 @@ var init_checks = __esm(() => {
$ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.format = def.format;
- if (def.pattern) {
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(def.pattern);
- }
- });
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
@@ -68636,13 +68973,8 @@ var init_checks = __esm(() => {
$ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = escapeRegex(def.includes);
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
@@ -68661,11 +68993,6 @@ var init_checks = __esm(() => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
@@ -68684,11 +69011,6 @@ var init_checks = __esm(() => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
@@ -68711,18 +69033,21 @@ var init_checks = __esm(() => {
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/doc.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/doc.js
class Doc {
- constructor(args = []) {
+ constructor(args = [], closed = {}) {
this.content = [];
this.indent = 0;
- if (this)
- this.args = args;
+ this.args = args;
+ this.closed = closed;
}
indented(fn) {
this.indent += 1;
- fn(this);
- this.indent -= 1;
+ try {
+ fn(this);
+ } finally {
+ this.indent -= 1;
+ }
}
write(arg) {
if (typeof arg === "function") {
@@ -68741,25 +69066,106 @@ class Doc {
}
compile() {
const F = Function;
- const args = this?.args;
const content = this?.content ?? [``];
- const lines = [...content.map((x) => ` ${x}`)];
- return new F(...args, lines.join(`
-`));
+ const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {
+${content.join(`
+`)}
+};`);
+ return factory(...Object.values(this.closed));
}
}
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/versions.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/versions.js
var version;
var init_versions = __esm(() => {
version = {
major: 4,
- minor: 4,
- patch: 3
+ minor: 6,
+ patch: 5
};
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/schemas.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/schemas.js
+async function validateAsync2(inst, value) {
+ const ctx = { async: true };
+ return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx);
+}
+function standardProps(inst) {
+ return {
+ validate: (value) => {
+ const ctx = { async: false };
+ try {
+ const r = inst._zod.run({ value, issues: [] }, ctx);
+ if (!(r instanceof Promise))
+ return toStandardResult(r, ctx);
+ } catch (_) {}
+ return validateAsync2(inst, value);
+ },
+ vendor: "zod",
+ version: 1
+ };
+}
+function canParseURL(input) {
+ try {
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function")
+ return URL.canParse(input);
+ new URL(input);
+ return true;
+ } catch {
+ return false;
+ }
+}
+function validateURL(trimmed, def) {
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
+ return canParseURL(trimmed) || URL_UNPARSEABLE;
+ }
+ return parseURLObject(trimmed, def);
+}
+function parseURLObject(trimmed, def) {
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
+ return URL_BAD_FORMAT;
+ }
+ try {
+ if (typeof URL !== "undefined") {
+ const URLStatic = URL;
+ if (typeof URLStatic.parse === "function")
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
+ }
+ return new URL(trimmed);
+ } catch {
+ return URL_UNPARSEABLE;
+ }
+}
+function stripTabAndNewline(value) {
+ return value.replace(asciiTabOrNewline, "");
+}
+function urlHostnameOk(url, hostname) {
+ hostname.lastIndex = 0;
+ return hostname.test(url.hostname);
+}
+function urlProtocolOk(url, protocol) {
+ protocol.lastIndex = 0;
+ return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
+}
+function isValidIPv6(value) {
+ if (!ipv6Alphabet.test(value))
+ return false;
+ return canParseURL(`http://[${value}]`);
+}
+function isValidCIDRv6(value) {
+ const parts = value.split("/");
+ if (parts.length !== 2)
+ return false;
+ const [address, prefix] = parts;
+ if (!prefix)
+ return false;
+ const prefixNum = Number(prefix);
+ if (`${prefixNum}` !== prefix)
+ return false;
+ if (prefixNum < 0 || prefixNum > 128)
+ return false;
+ return isValidIPv6(address);
+}
function isValidBase64(data) {
if (data === "")
return true;
@@ -68775,7 +69181,7 @@ function isValidBase64(data) {
}
}
function isValidBase64URL(data) {
- if (!base64url.test(data))
+ if (!base64urlCharset.test(data))
return false;
const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
@@ -68807,15 +69213,19 @@ function handleArrayResult(result, final, index) {
}
final.value[index] = result.value;
}
-function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
+function handlePropertyResult(result, final, key, input, optin, optout) {
const isPresent = key in input;
+ const isOptionalOut = optout === "optional";
+ if (!isPresent && isOptionalOut && optin === "optional") {
+ return;
+ }
if (result.issues.length) {
- if (isOptionalIn && isOptionalOut && !isPresent) {
+ if (optin !== undefined && isOptionalOut && !isPresent) {
return;
}
final.issues.push(...prefixIssues(key, result.issues));
}
- if (!isPresent && !isOptionalIn) {
+ if (!isPresent && optin === undefined) {
if (!result.issues.length) {
final.issues.push({
code: "invalid_type",
@@ -68827,7 +69237,7 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona
return;
}
if (result.value === undefined) {
- if (isPresent) {
+ if (isPresent || optin === "defaulted" && !isOptionalOut) {
final.value[key] = undefined;
}
} else {
@@ -68836,41 +69246,54 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona
}
function normalizeDef(def) {
const keys = Object.keys(def.shape);
- for (const k of keys) {
+ const ownSymbols = Object.getOwnPropertySymbols(def.shape);
+ const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
+ const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
+ for (const k of allKeys) {
if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
+ throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
}
}
const okeys = optionalKeys(def.shape);
return {
...def,
- keys,
+ allKeys,
+ symbolKeys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
}
-function handleCatchall(proms, input, payload, ctx, def, inst) {
+function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {
const unrecognized = [];
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
- const isOptionalIn = _catchall.optin === "optional";
- const isOptionalOut = _catchall.optout === "optional";
+ const optin = _catchall.optin;
+ const optout = _catchall.optout;
+ let seen = 0;
for (const key in input) {
- if (key === "__proto__")
- continue;
+ if (abortEarly && payload.issues.length !== seen) {
+ if (aborted(payload, seen))
+ break;
+ seen = payload.issues.length;
+ }
if (keySet.has(key))
continue;
+ if (key === "__proto__") {
+ if (t === "never")
+ unrecognized.push(key);
+ continue;
+ }
if (t === "never") {
unrecognized.push(key);
continue;
}
const r = _catchall.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
} else {
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ handlePropertyResult(r, payload, key, input, optin, optout);
}
}
if (unrecognized.length) {
@@ -68878,7 +69301,8 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
code: "unrecognized_keys",
keys: unrecognized,
input,
- inst
+ inst,
+ continue: true
});
}
if (!proms.length)
@@ -68907,6 +69331,24 @@ function handleUnionResults(results, final, inst, ctx) {
});
return final;
}
+function discriminatorMap(def) {
+ const map = new Map;
+ for (const option of def.options) {
+ const values = option._zod.propValues?.[def.discriminator];
+ if (!values || values.size === 0)
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ for (const value of values) {
+ if (map.has(value)) {
+ if (value !== undefined)
+ throw new Error(`Duplicate discriminator value "${String(value)}"`);
+ map.set(value, null);
+ } else {
+ map.set(value, option);
+ }
+ }
+ }
+ return map;
+}
function mergeValues(a, b) {
if (a === b) {
return { valid: true, data: a };
@@ -68918,7 +69360,11 @@ function mergeValues(a, b) {
const bKeys = Object.keys(b);
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
+ if (Object.prototype.hasOwnProperty.call(newObj, "__proto__"))
+ delete newObj.__proto__;
for (const key of sharedKeys) {
+ if (key === "__proto__")
+ continue;
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return {
@@ -68954,47 +69400,57 @@ function mergeValues(a, b) {
function handleIntersectionResults(result, left, right) {
const unrecKeys = new Map;
let unrecIssue;
- for (const iss of left.issues) {
- if (iss.code === "unrecognized_keys") {
+ const keyIssues = new Map;
+ const collect = (iss, side) => {
+ let keys;
+ if (iss.code === "unrecognized_keys" && !iss.path?.length) {
unrecIssue ?? (unrecIssue = iss);
- for (const k of iss.keys) {
- if (!unrecKeys.has(k))
- unrecKeys.set(k, {});
- unrecKeys.get(k).l = true;
- }
+ keys = iss.keys;
+ } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
+ const k = String(iss.path[0]);
+ if (!keyIssues.has(k))
+ keyIssues.set(k, iss);
+ keys = [k];
} else {
- result.issues.push(iss);
+ return false;
+ }
+ for (const k of keys) {
+ if (!unrecKeys.has(k))
+ unrecKeys.set(k, {});
+ unrecKeys.get(k)[side] = true;
}
+ return true;
+ };
+ for (const iss of left.issues) {
+ if (!collect(iss, "l"))
+ result.issues.push(iss);
}
for (const iss of right.issues) {
- if (iss.code === "unrecognized_keys") {
- for (const k of iss.keys) {
- if (!unrecKeys.has(k))
- unrecKeys.set(k, {});
- unrecKeys.get(k).r = true;
- }
- } else {
+ if (!collect(iss, "r"))
result.issues.push(iss);
- }
}
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
- if (bothKeys.length && unrecIssue) {
- result.issues.push({ ...unrecIssue, keys: bothKeys });
+ if (bothKeys.length) {
+ const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
+ if (aggregated.length)
+ result.issues.push({ ...unrecIssue, keys: aggregated });
+ for (const k of bothKeys) {
+ if (!aggregated.includes(k) && keyIssues.has(k))
+ result.issues.push(keyIssues.get(k));
+ }
}
- if (aborted(result))
- return result;
const merged = mergeValues(left.value, right.value);
if (!merged.valid) {
+ if (aborted(result))
+ return result;
throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
}
result.value = merged.data;
return result;
}
-function handleOptionalResult(result, input) {
- if (input === undefined && (result.issues.length || result.fallback)) {
- return { issues: [], value: undefined };
- }
- return result;
+function handleOptionalResult(payload, result) {
+ payload.value = result.issues.length ? undefined : result.value;
+ return payload;
}
function handleDefaultResult(payload, def) {
if (payload.value === undefined) {
@@ -69013,15 +69469,33 @@ function handleNonOptionalResult(payload, inst) {
}
return payload;
}
+function handleCatchResult(payload, result, def, ctx) {
+ if (!result.issues.length) {
+ payload.value = result.value;
+ if (result.memo)
+ payload.memo = true;
+ return payload;
+ }
+ payload.value = def.catchValue({
+ ...result,
+ value: payload.value,
+ error: {
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ },
+ input: payload.value
+ });
+ return payload;
+}
function handlePipeResult(left, next, ctx) {
- if (left.issues.length) {
+ if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
left.aborted = true;
return left;
}
- return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
}
function handleReadonlyResult(payload) {
- payload.value = Object.freeze(payload.value);
+ if (!payload.memo)
+ payload.value = Object.freeze(payload.value);
return payload;
}
function handleRefineResult(result, payload, input, inst) {
@@ -69038,11 +69512,10 @@ function handleRefineResult(result, payload, input, inst) {
payload.issues.push(issue(_iss));
}
}
-var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodUnknown, $ZodNever, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodPreprocess, $ZodReadonly, $ZodCustom;
+var $ZodType, toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT = 1, URL_UNPARSEABLE = 2, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodUnknown, $ZodNever, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodPreprocess, $ZodReadonly, $ZodCustom;
var init_schemas = __esm(() => {
init_checks();
init_core();
- init_parse();
init_regexes();
init_util();
init_versions();
@@ -69053,10 +69526,8 @@ var init_schemas = __esm(() => {
inst._zod.def = def;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
- const checks = [...inst._zod.def.checks ?? []];
- if (inst._zod.traits.has("$ZodCheck")) {
- checks.unshift(inst);
- }
+ const defChecks = inst._zod.def.checks;
+ const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];
for (const ch of checks) {
for (const fn of ch._zod.onattach) {
fn(inst);
@@ -69069,6 +69540,8 @@ var init_schemas = __esm(() => {
});
} else {
const runChecks = (payload, checks, ctx) => {
+ if (payload.memo)
+ return payload;
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
@@ -69092,6 +69565,7 @@ var init_schemas = __esm(() => {
const nextLen = payload.issues.length;
if (nextLen === currLen)
return;
+ attachSchema(payload.issues, currLen, inst);
if (!isAborted)
isAborted = aborted(payload, currLen);
});
@@ -69099,6 +69573,7 @@ var init_schemas = __esm(() => {
const nextLen = payload.issues.length;
if (nextLen === currLen)
continue;
+ attachSchema(payload.issues, currLen, inst);
if (!isAborted)
isAborted = aborted(payload, currLen);
}
@@ -69145,22 +69620,17 @@ var init_schemas = __esm(() => {
return runChecks(result, checks, ctx);
};
}
- defineLazy(inst, "~standard", () => ({
- validate: (value) => {
- try {
- const r = safeParse(inst, value);
- return r.success ? { value: r.data } : { issues: r.error?.issues };
- } catch (_) {
- return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
- }
- },
- vendor: "zod",
- version: 1
- }));
+ }, {
+ get "~standard"() {
+ return hide(this, "~standard", standardProps(this));
+ },
+ set "~standard"(value) {
+ own(this, "~standard", value);
+ }
});
$ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
+ inst._zod.pattern = def.pattern ?? anyString;
inst._zod.parse = (payload, _) => {
if (def.coerce)
try {
@@ -69209,58 +69679,61 @@ var init_schemas = __esm(() => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
+ asciiTabOrNewline = /[\t\n\r]/g;
$ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const trimmed = payload.value.trim();
- if (!def.normalize && def.protocol?.source === httpProtocol.source) {
- if (!/^https?:\/\//i.test(trimmed)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid URL format",
- input: payload.value,
- inst,
- continue: !def.abort
- });
- return;
- }
+ const url = validateURL(trimmed, def);
+ if (url === URL_BAD_FORMAT) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid URL format",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
}
- const url = new URL(trimmed);
- if (def.hostname) {
- def.hostname.lastIndex = 0;
- if (!def.hostname.test(url.hostname)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid hostname",
- pattern: def.hostname.source,
- input: payload.value,
- inst,
- continue: !def.abort
- });
- }
+ if (url === URL_UNPARSEABLE) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
}
- if (def.protocol) {
- def.protocol.lastIndex = 0;
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid protocol",
- pattern: def.protocol.source,
- input: payload.value,
- inst,
- continue: !def.abort
- });
- }
+ if (url === true) {
+ payload.value = stripTabAndNewline(trimmed);
+ return;
}
- if (def.normalize) {
- payload.value = url.href;
- } else {
- payload.value = trimmed;
+ if (def.hostname && !urlHostnameOk(url, def.hostname)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid hostname",
+ pattern: def.hostname.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
}
+ if (def.protocol && !urlProtocolOk(url, def.protocol)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid protocol",
+ pattern: def.protocol.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
return;
} catch (_) {
payload.issues.push({
@@ -69278,7 +69751,9 @@ var init_schemas = __esm(() => {
$ZodStringFormat.init(inst, def);
});
$ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
- def.pattern ?? (def.pattern = nanoid);
+ if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))
+ throw new Error(`Invalid nanoid length: ${def.length}`);
+ def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length));
$ZodStringFormat.init(inst, def);
});
$ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
@@ -69320,16 +69795,13 @@ var init_schemas = __esm(() => {
$ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.format = `ipv4`;
});
+ ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
$ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.format = `ipv6`;
inst._zod.check = (payload) => {
- try {
- new URL(`http://[${payload.value}]`);
- } catch {
+ if (!isValidIPv6(payload.value)) {
payload.issues.push({
code: "invalid_format",
format: "ipv6",
@@ -69348,20 +69820,7 @@ var init_schemas = __esm(() => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
- const parts = payload.value.split("/");
- try {
- if (parts.length !== 2)
- throw new Error;
- const [address, prefix] = parts;
- if (!prefix)
- throw new Error;
- const prefixNum = Number(prefix);
- if (`${prefixNum}` !== prefix)
- throw new Error;
- if (prefixNum < 0 || prefixNum > 128)
- throw new Error;
- new URL(`http://[${address}]`);
- } catch {
+ if (!isValidCIDRv6(payload.value)) {
payload.issues.push({
code: "invalid_format",
format: "cidrv6",
@@ -69372,10 +69831,10 @@ var init_schemas = __esm(() => {
}
};
});
+ base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
$ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
- def.pattern ?? (def.pattern = base64);
+ def.pattern ?? (def.pattern = base64Charset);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.contentEncoding = "base64";
inst._zod.check = (payload) => {
if (isValidBase64(payload.value))
return;
@@ -69388,10 +69847,10 @@ var init_schemas = __esm(() => {
});
};
});
+ base64urlCharset = /^[A-Za-z0-9_-]*$/;
$ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
- def.pattern ?? (def.pattern = base64url);
+ def.pattern ?? (def.pattern = base64urlCharset);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.contentEncoding = "base64url";
inst._zod.check = (payload) => {
if (isValidBase64URL(payload.value))
return;
@@ -69424,7 +69883,7 @@ var init_schemas = __esm(() => {
});
$ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.pattern = inst._zod.bag.pattern ?? number;
+ inst._zod.pattern = number;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce)
try {
@@ -69434,7 +69893,7 @@ var init_schemas = __esm(() => {
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
return payload;
}
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined;
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : undefined : undefined;
payload.issues.push({
expected: "number",
code: "invalid_type",
@@ -69487,6 +69946,8 @@ var init_schemas = __esm(() => {
});
$ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
$ZodType.init(inst, def);
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!Array.isArray(input)) {
@@ -69498,8 +69959,9 @@ var init_schemas = __esm(() => {
});
return payload;
}
- payload.value = Array(input.length);
+ payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);
const proms = [];
+ const abortEarly = ctx?.abortEarly;
for (let i = 0;i < input.length; i++) {
const item = input[i];
const result = def.element._zod.run({
@@ -69510,6 +69972,8 @@ var init_schemas = __esm(() => {
proms.push(result.then((result) => handleArrayResult(result, payload, i)));
} else {
handleArrayResult(result, payload, i);
+ if (abortEarly && result.issues.length !== 0 && aborted(result))
+ break;
}
}
if (proms.length) {
@@ -69518,31 +69982,35 @@ var init_schemas = __esm(() => {
return payload;
};
});
+ NO_SYMBOL_KEYS = [];
$ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
const desc = Object.getOwnPropertyDescriptor(def, "shape");
- if (!desc?.get) {
- const sh = def.shape;
- Object.defineProperty(def, "shape", {
- get: () => {
- const newSh = { ...sh };
- Object.defineProperty(def, "shape", {
- value: newSh
- });
- return newSh;
- }
- });
+ const sh = desc?.get ? desc.get.raw : def.shape ?? {};
+ if (sh) {
+ const get = () => {
+ const newSh = { ...sh };
+ Object.defineProperty(def, "shape", { value: newSh });
+ get.raw = newSh;
+ return newSh;
+ };
+ get.raw = sh;
+ Object.defineProperty(def, "shape", { get });
}
const _normalized = cached(() => normalizeDef(def));
- defineLazy(inst._zod, "propValues", () => {
- const shape = def.shape;
+ defineLazyInternal(inst, "propValues", (zod) => {
+ const shape = zod.def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
- propValues[key] ?? (propValues[key] = new Set);
+ if (!Object.prototype.hasOwnProperty.call(propValues, key)) {
+ assignProp(propValues, key, new Set);
+ }
for (const v of field.values)
propValues[key].add(v);
+ if (field.optin !== undefined)
+ propValues[key].add(undefined);
}
}
return propValues;
@@ -69550,6 +70018,8 @@ var init_schemas = __esm(() => {
const isObject2 = isObject;
const catchall = def.catchall;
let value;
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
@@ -69562,79 +70032,93 @@ var init_schemas = __esm(() => {
});
return payload;
}
- payload.value = {};
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const proms = [];
const shape = value.shape;
- for (const key of value.keys) {
+ const abortEarly = ctx?.abortEarly;
+ let seen = payload.issues.length;
+ for (const key of value.allKeys) {
+ if (abortEarly && payload.issues.length !== seen) {
+ if (aborted(payload, seen))
+ break;
+ seen = payload.issues.length;
+ }
+ if (key === "__proto__")
+ continue;
const el = shape[key];
- const isOptionalIn = el._zod.optin === "optional";
- const isOptionalOut = el._zod.optout === "optional";
+ const optin = el._zod.optin;
+ const optout = el._zod.optout;
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
} else {
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ handlePropertyResult(r, payload, key, input, optin, optout);
}
}
if (!catchall) {
return proms.length ? Promise.all(proms).then(() => payload) : payload;
}
- return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
};
});
$ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
$ZodObject.init(inst, def);
const superParse = inst._zod.parse;
const _normalized = cached(() => normalizeDef(def));
+ const memo = globalConfig.memoizer;
const generateFastpass = (shape) => {
- const doc = new Doc(["shape", "payload", "ctx"]);
const normalized = _normalized.value;
- const parseStr = (key) => {
- const k = esc(key);
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
- };
+ const syms = normalized.symbolKeys;
+ const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms });
+ const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
+ const prefixStr = (id, k) => `
+ let ${id}_ab = false;
+ for (let i = 0; i < ${id}.issues.length; i++) {
+ const iss = ${id}.issues[i];
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
+ payload.issues.push(iss);
+ if (iss.continue !== true) ${id}_ab = true;
+ }
+ if (${id}_ab && ctx && ctx.abortEarly) {
+ payload.value = newResult;
+ return payload;
+ }`;
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
- for (const key of normalized.keys) {
+ for (const key of normalized.allKeys) {
ids[key] = `key_${counter++}`;
}
- doc.write(`const newResult = {};`);
- for (const key of normalized.keys) {
+ doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);
+ for (const key of normalized.allKeys) {
+ if (key === "__proto__")
+ continue;
const id = ids[key];
- const k = esc(key);
+ const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
+ const isPresent = `${k} in input`;
const schema = shape[key];
- const isOptionalIn = schema?._zod?.optin === "optional";
+ const optin = schema?._zod?.optin;
+ const isOptionalIn = optin !== undefined;
const isOptionalOut = schema?._zod?.optout === "optional";
- doc.write(`const ${id} = ${parseStr(key)};`);
+ doc.write(`const ${id} = ${parseStr(k)};`);
if (isOptionalIn && isOptionalOut) {
+ const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
doc.write(`
- if (${id}.issues.length) {
- if (${k} in input) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ const ${id}_present = ${isPresent};
+ if (!${id}.issues.length || ${id}_present) {
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
- }
-
- if (${id}.value === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
+
+ if (${assign}) {
+ newResult[${k}] = ${id}.value;
}
- } else {
- newResult[${k}] = ${id}.value;
}
-
+
`);
} else if (!isOptionalIn) {
doc.write(`
- const ${id}_present = ${k} in input;
- if (${id}.issues.length) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ const ${id}_present = ${isPresent};
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
if (!${id}_present && !${id}.issues.length) {
payload.issues.push({
@@ -69643,41 +70127,36 @@ var init_schemas = __esm(() => {
input: undefined,
path: [${k}]
});
+ if (ctx && ctx.abortEarly) {
+ payload.value = newResult;
+ return payload;
+ }
}
if (${id}_present) {
- if (${id}.value === undefined) {
- newResult[${k}] = undefined;
- } else {
- newResult[${k}] = ${id}.value;
- }
+ newResult[${k}] = ${id}.value;
}
`);
} else {
doc.write(`
- if (${id}.issues.length) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
- }
-
- if (${id}.value === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
- }
- } else {
+ if (${id}.issues.length) {${prefixStr(id, k)}
+ }
+ `);
+ if (optin === "defaulted") {
+ doc.write(`newResult[${k}] = ${id}.value;`);
+ } else {
+ doc.write(`
+ if (${id}.value !== undefined || ${isPresent}) {
newResult[${k}] = ${id}.value;
}
-
`);
+ }
}
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
- const fn = doc.compile();
- return (payload, ctx) => fn(shape, payload, ctx);
+ return doc.compile();
};
let fastpass;
const isObject2 = isObject;
@@ -69704,24 +70183,24 @@ var init_schemas = __esm(() => {
payload = fastpass(payload, ctx);
if (!catchall)
return payload;
- return handleCatchall([], input, payload, ctx, value, inst);
+ return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);
}
return superParse(payload, ctx);
};
});
$ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "values", () => {
- if (def.options.every((o) => o._zod.values)) {
- return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
+ defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== undefined) ? "optional" : undefined);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
+ defineLazyInternal(inst, "values", (zod) => {
+ if (zod.def.options.every((o) => o._zod.values)) {
+ return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));
}
return;
});
- defineLazy(inst._zod, "pattern", () => {
- if (def.options.every((o) => o._zod.pattern)) {
- const patterns = def.options.map((o) => o._zod.pattern);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ if (zod.def.options.every((o) => o._zod.pattern)) {
+ const patterns = zod.def.options.map((o) => o._zod.pattern);
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
}
return;
@@ -69758,38 +70237,35 @@ var init_schemas = __esm(() => {
def.inclusive = false;
$ZodUnion.init(inst, def);
const _super = inst._zod.parse;
- defineLazy(inst._zod, "propValues", () => {
+ defineLazyInternal(inst, "propValues", (zod) => {
const propValues = {};
- for (const option of def.options) {
+ let undefinedCount = 0;
+ for (const option of zod.def.options) {
const pv = option._zod.propValues;
if (!pv || Object.keys(pv).length === 0)
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
+ if (pv[zod.def.discriminator]?.has(undefined))
+ undefinedCount++;
for (const [k, v] of Object.entries(pv)) {
- if (!propValues[k])
- propValues[k] = new Set;
+ if (!Object.prototype.hasOwnProperty.call(propValues, k)) {
+ assignProp(propValues, k, new Set);
+ }
for (const val of v) {
propValues[k].add(val);
}
}
}
+ if (!zod.def.unionFallback && undefinedCount > 1)
+ propValues[zod.def.discriminator]?.delete(undefined);
return propValues;
});
- const disc = cached(() => {
- const opts = def.options;
- const map = new Map;
- for (const o of opts) {
- const values = o._zod.propValues?.[def.discriminator];
- if (!values || values.size === 0)
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
- for (const v of values) {
- if (map.has(v)) {
- throw new Error(`Duplicate discriminator value "${String(v)}"`);
- }
- map.set(v, o);
- }
+ def.options.forEach((option, i) => {
+ const propShape = rawShape(option._zod.def);
+ if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {
+ throw new Error(`Invalid discriminated union option at index "${i}"`);
}
- return map;
});
+ const disc = cached(() => discriminatorMap(def));
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isObject(input)) {
@@ -69801,8 +70277,9 @@ var init_schemas = __esm(() => {
});
return payload;
}
- const opt = disc.value.get(input?.[def.discriminator]);
- if (opt) {
+ const value = input?.[def.discriminator];
+ const opt = disc.value.get(value);
+ if (opt && (value !== undefined || ctx.direction !== "backward")) {
return opt._zod.run(payload, ctx);
}
if (def.unionFallback || ctx.direction === "backward") {
@@ -69813,7 +70290,7 @@ var init_schemas = __esm(() => {
errors: [],
note: "No matching discriminator",
discriminator: def.discriminator,
- options: Array.from(disc.value.keys()),
+ options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),
input,
path: [def.discriminator],
inst
@@ -69838,6 +70315,8 @@ var init_schemas = __esm(() => {
});
$ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
$ZodType.init(inst, def);
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isPlainObject3(input)) {
@@ -69851,12 +70330,14 @@ var init_schemas = __esm(() => {
}
const proms = [];
const values = def.keyType._zod.values;
- if (values) {
- payload.value = {};
+ if (values && !def.partial) {
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const recordKeys = new Set;
for (const key of values) {
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
recordKeys.add(typeof key === "number" ? key.toString() : key);
+ if (key === "__proto__")
+ continue;
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
@@ -69873,6 +70354,8 @@ var init_schemas = __esm(() => {
continue;
}
const outKey = keyResult.value;
+ if (outKey === "__proto__")
+ continue;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
@@ -69892,8 +70375,14 @@ var init_schemas = __esm(() => {
let unrecognized;
for (const key in input) {
if (!recordKeys.has(key)) {
- unrecognized = unrecognized ?? [];
- unrecognized.push(key);
+ if (def.mode === "loose") {
+ if (key === "__proto__")
+ continue;
+ payload.value[key] = input[key];
+ } else {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
+ }
}
}
if (unrecognized && unrecognized.length > 0) {
@@ -69901,11 +70390,13 @@ var init_schemas = __esm(() => {
code: "unrecognized_keys",
input,
inst,
- keys: unrecognized
+ keys: unrecognized,
+ continue: true
});
}
} else {
- payload.value = {};
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
+ let unrecognized;
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__")
continue;
@@ -69928,6 +70419,9 @@ var init_schemas = __esm(() => {
if (keyResult.issues.length) {
if (def.mode === "loose") {
payload.value[key] = input[key];
+ } else if (values) {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
} else {
payload.issues.push({
code: "invalid_key",
@@ -69940,21 +70434,33 @@ var init_schemas = __esm(() => {
}
continue;
}
+ const outKey = keyResult.value;
+ if (outKey === "__proto__")
+ continue;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
if (result.issues.length) {
payload.issues.push(...prefixIssues(key, result.issues));
}
- payload.value[keyResult.value] = result.value;
+ payload.value[outKey] = result.value;
}));
} else {
if (result.issues.length) {
payload.issues.push(...prefixIssues(key, result.issues));
}
- payload.value[keyResult.value] = result.value;
+ payload.value[outKey] = result.value;
}
}
+ if (unrecognized && unrecognized.length > 0) {
+ payload.issues.push({
+ code: "unrecognized_keys",
+ input,
+ inst,
+ keys: unrecognized,
+ continue: true
+ });
+ }
}
if (proms.length) {
return Promise.all(proms).then(() => payload);
@@ -69967,7 +70473,10 @@ var init_schemas = __esm(() => {
const values = getEnumValues(def.entries);
const valuesSet = new Set(values);
inst._zod.values = valuesSet;
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k));
+ return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$");
+ });
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (valuesSet.has(input)) {
@@ -69984,12 +70493,12 @@ var init_schemas = __esm(() => {
});
$ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
$ZodType.init(inst, def);
- if (def.values.length === 0) {
- throw new Error("Cannot create literal schema with no valid values");
- }
const values = new Set(def.values);
inst._zod.values = values;
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const vals = zod.def.values;
+ return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$");
+ });
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (values.has(input)) {
@@ -70007,6 +70516,7 @@ var init_schemas = __esm(() => {
$ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
+ globalConfig.memoizer?.guard(inst);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
throw new $ZodEncodeError(inst.constructor.name);
@@ -70016,7 +70526,6 @@ var init_schemas = __esm(() => {
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
return output.then((output) => {
payload.value = output;
- payload.fallback = true;
return payload;
});
}
@@ -70024,53 +70533,51 @@ var init_schemas = __esm(() => {
throw new $ZodAsyncError;
}
payload.value = _out;
- payload.fallback = true;
return payload;
};
});
$ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
inst._zod.optout = "optional";
- defineLazy(inst._zod, "values", () => {
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
+ defineLazyInternal(inst, "values", (zod) => {
+ const values = zod.def.innerType._zod.values;
+ return values ? new Set([...values, undefined]) : undefined;
});
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def.innerType._zod.pattern;
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
});
inst._zod.parse = (payload, ctx) => {
- if (def.innerType._zod.optin === "optional") {
- const input = payload.value;
- const result = def.innerType._zod.run(payload, ctx);
- if (result instanceof Promise)
- return result.then((r) => handleOptionalResult(r, input));
- return handleOptionalResult(result, input);
- }
if (payload.value === undefined) {
- return payload;
+ if (def.innerType._zod.optin !== "defaulted")
+ return payload;
+ const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ return result.then((result) => handleOptionalResult(payload, result));
+ return handleOptionalResult(payload, result);
}
return def.innerType._zod.run(payload, ctx);
};
});
$ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
$ZodOptional.init(inst, def);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
- defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
+ defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern);
inst._zod.parse = (payload, ctx) => {
return def.innerType._zod.run(payload, ctx);
};
});
$ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def.innerType._zod.pattern;
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
});
- defineLazy(inst._zod, "values", () => {
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
+ defineLazyInternal(inst, "values", (zod) => {
+ return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === null)
@@ -70080,8 +70587,8 @@ var init_schemas = __esm(() => {
});
$ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.optin = "defaulted";
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -70099,8 +70606,8 @@ var init_schemas = __esm(() => {
});
$ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.optin = "defaulted";
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -70113,8 +70620,8 @@ var init_schemas = __esm(() => {
});
$ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "values", () => {
- const v = def.innerType._zod.values;
+ defineLazyInternal(inst, "values", (zod) => {
+ const v = zod.def.innerType._zod.values;
return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
});
inst._zod.parse = (payload, ctx) => {
@@ -70127,52 +70634,26 @@ var init_schemas = __esm(() => {
});
$ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
}
- const result = def.innerType._zod.run(payload, ctx);
+ const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
if (result instanceof Promise) {
- return result.then((result) => {
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- payload.fallback = true;
- }
- return payload;
- });
- }
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- payload.fallback = true;
+ return result.then((result) => handleCatchResult(payload, result, def, ctx));
}
- return payload;
+ return handleCatchResult(payload, result, def, ctx);
};
});
$ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "values", () => def.in._zod.values);
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
+ defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
const right = def.out._zod.run(payload, ctx);
@@ -70193,10 +70674,10 @@ var init_schemas = __esm(() => {
});
$ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
- defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
- defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -70226,7 +70707,276 @@ var init_schemas = __esm(() => {
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/en.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/memoizer.js
+function isRef(value) {
+ return value !== null && typeof value === "object";
+}
+function cloneIssues(issues) {
+ return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
+}
+function isRecursive(inst, stack, resolve) {
+ const cached = recursive.get(inst);
+ if (cached !== undefined)
+ return cached ? PROVEN : NONE;
+ if (stack.has(inst))
+ return PROVEN;
+ stack.add(inst);
+ let result = NONE;
+ const check = (child) => {
+ if (result !== PROVEN && child?._zod) {
+ const answer = isRecursive(child, stack, resolve);
+ if (answer > result)
+ result = answer;
+ }
+ };
+ const shape = (sh, spread) => {
+ let answer = NONE;
+ for (const key of Reflect.ownKeys(sh)) {
+ const desc = Object.getOwnPropertyDescriptor(sh, key);
+ if (spread && !desc.enumerable)
+ continue;
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
+ if (child > answer)
+ answer = child;
+ }
+ return answer;
+ };
+ const merge = (answer) => {
+ if (answer > result)
+ result = answer;
+ };
+ const def = inst._zod.def;
+ const kind = def.type;
+ switch (kind) {
+ case "object": {
+ const raw = rawShape(def);
+ merge(raw ? shape(raw, true) : ASSUMED);
+ check(def.catchall);
+ break;
+ }
+ case "array":
+ check(def.element);
+ break;
+ case "tuple":
+ for (const el of def.items)
+ check(el);
+ check(def.rest);
+ break;
+ case "record":
+ case "map":
+ check(def.keyType);
+ check(def.valueType);
+ break;
+ case "set":
+ check(def.valueType);
+ break;
+ case "union":
+ for (const el of def.options)
+ check(el);
+ break;
+ case "intersection":
+ check(def.left);
+ check(def.right);
+ break;
+ case "optional":
+ case "nullable":
+ case "default":
+ case "prefault":
+ case "catch":
+ case "readonly":
+ case "nonoptional":
+ case "promise":
+ case "success":
+ check(def.innerType);
+ break;
+ case "pipe":
+ check(def.in);
+ check(def.out);
+ break;
+ case "function":
+ check(def.input);
+ check(def.output);
+ break;
+ case "lazy": {
+ const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);
+ merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
+ break;
+ }
+ case "template_literal":
+ case "string":
+ case "number":
+ case "int":
+ case "boolean":
+ case "bigint":
+ case "symbol":
+ case "undefined":
+ case "null":
+ case "void":
+ case "never":
+ case "any":
+ case "unknown":
+ case "date":
+ case "nan":
+ case "enum":
+ case "literal":
+ case "file":
+ case "transform":
+ case "custom":
+ break;
+ default: {
+ for (const key in def) {
+ const desc = Object.getOwnPropertyDescriptor(def, key);
+ if (!desc || desc.get)
+ continue;
+ const value = desc.value;
+ if (!value || typeof value !== "object")
+ continue;
+ if (value._zod)
+ check(value);
+ else if (Array.isArray(value))
+ for (const el of value)
+ check(el);
+ }
+ }
+ }
+ stack.delete(inst);
+ return settle(inst, result);
+}
+function settle(inst, answer) {
+ if (answer !== ASSUMED)
+ recursive.set(inst, answer === PROVEN);
+ return answer;
+}
+function bucketFor(state, inst) {
+ let bucket = state.buckets.get(inst);
+ if (!bucket) {
+ bucket = new WeakMap;
+ state.buckets.set(inst, bucket);
+ }
+ return bucket;
+}
+function memoizer() {
+ return memo;
+}
+function isBackEdge(ctx, value) {
+ const backEdges = ctx[STATE]?.backEdges;
+ return backEdges !== undefined && isRef(value) && backEdges.has(value);
+}
+var $ZodCyclicError, STATE = "~memo", NO_ISSUES, recursive, NONE = 0, ASSUMED = 1, PROVEN = 2, handoff, open, memo;
+var init_memoizer = __esm(() => {
+ init_util();
+ $ZodCyclicError = class $ZodCyclicError extends Error {
+ constructor() {
+ super(`Cannot parse a reference cycle that closes through a transform`);
+ this.name = "ZodCyclicError";
+ }
+ };
+ NO_ISSUES = [];
+ recursive = /* @__PURE__ */ new WeakMap;
+ open = [];
+ memo = {
+ alloc(_inst, payload, empty) {
+ const bucket = handoff;
+ if (!bucket)
+ return empty;
+ handoff = undefined;
+ const entry = { value: empty, issues: null };
+ bucket.set(payload.value, entry);
+ open.push(entry);
+ return empty;
+ },
+ guard(inst) {
+ var _a;
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
+ inst._zod.deferred.push(() => {
+ const base = inst._zod.parse;
+ const wrapped = (payload, ctx) => {
+ if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value))
+ throw new $ZodCyclicError;
+ return base(payload, ctx);
+ };
+ inst._zod.parse = wrapped;
+ if (inst._zod.run === base)
+ inst._zod.run = wrapped;
+ });
+ },
+ attach(inst) {
+ var _a;
+ let isRecursiveInst;
+ let rechecked = false;
+ let lastCtx;
+ let lastBucket;
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
+ inst._zod.deferred.push(() => {
+ const base = inst._zod.parse;
+ const wrapped = (payload, ctx) => {
+ if (isRecursiveInst === undefined) {
+ const walked = isRecursive(inst, new Set, false);
+ if (walked === NONE) {
+ inst._zod.parse = base;
+ if (inst._zod.run === wrapped)
+ inst._zod.run = base;
+ return base(payload, ctx);
+ }
+ if (walked === PROVEN || rechecked)
+ isRecursiveInst = true;
+ else
+ rechecked = true;
+ }
+ const input = payload.value;
+ if (!isRef(input))
+ return base(payload, ctx);
+ let state = ctx[STATE];
+ if (!state) {
+ state = { buckets: new WeakMap, backEdges: undefined };
+ ctx[STATE] = state;
+ }
+ let bucket;
+ if (lastCtx === ctx) {
+ bucket = lastBucket;
+ } else {
+ bucket = bucketFor(state, inst);
+ lastCtx = ctx;
+ lastBucket = bucket;
+ }
+ const hit = bucket.get(input);
+ if (hit) {
+ payload.value = hit.value;
+ if (hit.issues) {
+ if (hit.issues.length)
+ payload.issues.push(...cloneIssues(hit.issues));
+ } else {
+ payload.memo = true;
+ state.backEdges ?? (state.backEdges = new WeakSet);
+ state.backEdges.add(hit.value);
+ }
+ return payload;
+ }
+ handoff = bucket;
+ const depth = open.length;
+ const result = base(payload, ctx);
+ handoff = undefined;
+ const entry = open.length > depth ? open.pop() : undefined;
+ if (result instanceof Promise) {
+ return result.then((r) => {
+ if (entry)
+ entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
+ return r;
+ });
+ }
+ if (entry)
+ entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
+ return result;
+ };
+ inst._zod.parse = wrapped;
+ if (inst._zod.run === base)
+ inst._zod.run = wrapped;
+ });
+ }
+ };
+});
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/en.js
function en_default() {
return {
localeError: error()
@@ -70271,18 +71021,27 @@ var error = () => {
base64url: "base64url-encoded string",
json_string: "JSON string",
e164: "E.164 number",
+ currency_code: "currency code",
+ credit_card: "credit card number",
+ iban: "IBAN",
jwt: "JWT",
template_literal: "input"
};
const TypeDictionary = {
nan: "NaN"
};
+ function getTypeName(type, input) {
+ if (type === "number" && typeof input === "number" && !Number.isFinite(input)) {
+ return String(input);
+ }
+ return TypeDictionary[type] ?? type;
+ }
return (issue) => {
switch (issue.code) {
case "invalid_type": {
- const expected = TypeDictionary[issue.expected] ?? issue.expected;
+ const expected = getTypeName(issue.expected);
const receivedType = parsedType(issue.input);
- const received = TypeDictionary[receivedType] ?? receivedType;
+ const received = getTypeName(receivedType, issue.input);
return `Invalid input: expected ${expected}, received ${received}`;
}
case "invalid_value":
@@ -70290,14 +71049,14 @@ var error = () => {
return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
case "too_big": {
- const adj = issue.inclusive ? "<=" : "<";
+ const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
- const adj = issue.inclusive ? ">=" : ">";
+ const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
@@ -70328,6 +71087,9 @@ var error = () => {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `Invalid discriminator value. Expected ${opts}`;
}
+ if (issue.inclusive === false) {
+ return "Invalid input: more than one option matched";
+ }
return "Invalid input";
case "invalid_element":
return `Invalid value in ${issue.origin}`;
@@ -70340,10 +71102,10 @@ var init_en = __esm(() => {
init_util();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/index.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/index.js
var init_locales = () => {};
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/registries.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/registries.js
class $ZodRegistry {
constructor() {
this._map = new WeakMap;
@@ -70387,20 +71149,61 @@ class $ZodRegistry {
function registry() {
return new $ZodRegistry;
}
-var _a2, $output, $input, globalRegistry;
+var _a2, globalRegistry;
var init_registries = __esm(() => {
- $output = Symbol("ZodOutput");
- $input = Symbol("ZodInput");
(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
globalRegistry = globalThis.__zod_globalRegistry;
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/api.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/compile.js
+var INVALID2, FALLBACK_FLAG, WHEN_DEFAULTED_CHECKS, PATTERN_IS_COMPLETE;
+var init_compile = __esm(() => {
+ INVALID2 = Symbol.for("zod.compile.invalid");
+ FALLBACK_FLAG = Symbol.for("zod.compile.fallback");
+ WHEN_DEFAULTED_CHECKS = new Set([
+ "max_size",
+ "min_size",
+ "size_equals",
+ "max_length",
+ "min_length",
+ "length_equals"
+ ]);
+ PATTERN_IS_COMPLETE = new Set([
+ "cidrv4",
+ "cuid",
+ "cuid2",
+ "date",
+ "datetime",
+ "duration",
+ "e164",
+ "email",
+ "emoji",
+ "ends_with",
+ "guid",
+ "includes",
+ "ipv4",
+ "ksuid",
+ "lowercase",
+ "mac",
+ "nanoid",
+ "regex",
+ "starts_with",
+ "time",
+ "ulid",
+ "uppercase",
+ "uuid",
+ "xid"
+ ]);
+});
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/api.js
+function snapshotChecks(def) {
+ if (def.checks)
+ def.checks = [...def.checks];
+ return def;
+}
function _string(Class, params) {
- return new Class({
- type: "string",
- ...normalizeParams(params)
- });
+ return new Class(snapshotChecks({ type: "string", ...normalizeParams(params) }));
}
function _email(Class, params) {
return new Class({
@@ -70640,11 +71443,7 @@ function _isoDuration(Class, params) {
});
}
function _number(Class, params) {
- return new Class({
- type: "number",
- checks: [],
- ...normalizeParams(params)
- });
+ return new Class(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) }));
}
function _int(Class, params) {
return new Class({
@@ -70826,7 +71625,8 @@ function _superRefine(fn, params) {
if (_issue.fatal)
_issue.continue = false;
_issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
+ if (!("input" in _issue))
+ _issue.input = payload.value;
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
@@ -70849,7 +71649,17 @@ var init_api = __esm(() => {
init_util();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/to-json-schema.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/to-json-schema.js
+function assignProps(target, ...sources) {
+ for (const source of sources) {
+ for (const key of Reflect.ownKeys(source)) {
+ if (Object.prototype.propertyIsEnumerable.call(source, key)) {
+ assignProp(target, key, source[key]);
+ }
+ }
+ }
+ return target;
+}
function initializeContext(params) {
let target = params?.target ?? "draft-2020-12";
if (target === "draft-4")
@@ -70865,12 +71675,25 @@ function initializeContext(params) {
io: params?.io ?? "output",
counter: 0,
seen: new Map,
+ sharedDefsExtractedFor: undefined,
+ sharedEmitDoneFor: undefined,
cycles: params?.cycles ?? "ref",
reused: params?.reused ?? "inline",
+ intersections: [],
+ deferred: [],
external: params?.external ?? undefined
};
}
-function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
+function handleUnrepresentable(schema, ctx, json, params, message) {
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) : ctx.unrepresentable;
+ if (result === "any")
+ return false;
+ if (result === undefined || result === "throw")
+ throw new Error(message);
+ Object.assign(json, result);
+ return true;
+}
+function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {
var _a;
const def = schema._zod.def;
const seen = ctx.seen.get(schema);
@@ -70884,6 +71707,8 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
}
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
ctx.seen.set(schema, result);
+ ctx.sharedDefsExtractedFor = undefined;
+ ctx.sharedEmitDoneFor = undefined;
const overrideSchema = schema._zod.toJSONSchema?.();
if (overrideSchema) {
result.schema = overrideSchema;
@@ -70907,13 +71732,13 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
if (parent) {
if (!result.ref)
result.ref = parent;
- process3(parent, ctx, params);
+ processSchema(parent, ctx, params);
ctx.seen.get(parent).isParent = true;
}
}
const meta = ctx.metadataRegistry.get(schema);
if (meta)
- Object.assign(result.schema, meta);
+ assignProps(result.schema, meta);
if (ctx.io === "input" && isTransforming(schema)) {
delete result.schema.examples;
delete result.schema.default;
@@ -70924,10 +71749,15 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
const _result = ctx.seen.get(schema);
return _result.schema;
}
+function encodeJSONPointerSegment(segment) {
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
+}
function extractDefs(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root)
throw new Error("Unprocessed schema. This is a bug in Zod.");
+ if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)
+ return;
const idToSchema = new Map;
for (const entry of ctx.seen.entries()) {
const id = ctx.metadataRegistry.get(entry[0])?.id;
@@ -70949,15 +71779,15 @@ function extractDefs(ctx, schema) {
}
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
entry[1].defId = id;
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
- }
- if (entry[1] === root) {
- return { ref: "#" };
+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };
}
const uriPrefix = `#`;
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
+ if (entry[1] === root && !entry[1].schema.id) {
+ return { ref: uriPrefix };
+ }
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
- return { defId, ref: defUriPrefix + defId };
+ return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };
};
const extractToDef = (entry) => {
if (entry[1].schema.$ref) {
@@ -71007,10 +71837,117 @@ function extractDefs(ctx, schema) {
if (seen.count > 1) {
if (ctx.reused === "ref") {
extractToDef(entry);
+ }
+ }
+ }
+ if (ctx.external)
+ ctx.sharedDefsExtractedFor = ctx.external;
+}
+function compactTypeUnion(schema) {
+ const options = schema.anyOf;
+ if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)
+ return;
+ const types = [];
+ for (const option of options) {
+ if (!option || typeof option !== "object")
+ return;
+ compactTypeUnion(option);
+ const keys = Object.keys(option);
+ if (keys.length !== 1 || keys[0] !== "type")
+ return;
+ const type = option.type;
+ for (const member of Array.isArray(type) ? type : [type]) {
+ if (typeof member !== "string")
+ return;
+ if (!types.includes(member))
+ types.push(member);
+ }
+ }
+ delete schema.anyOf;
+ schema.type = types.length === 1 ? types[0] : types;
+}
+function undeclaredConstraint(member) {
+ const extra = member.additionalProperties;
+ if (extra === undefined || extra === false || typeof extra !== "object" || extra === null)
+ return null;
+ return Object.keys(extra).length ? extra : null;
+}
+function foldObjects(members) {
+ const objects = [];
+ for (const member of members) {
+ if (typeof member !== "object" || member.type !== "object")
+ return null;
+ for (const key in member) {
+ if (!FOLDABLE_KEYS.has(key))
+ return null;
+ }
+ objects.push(member);
+ }
+ const properties = {};
+ const required = new Set;
+ for (const object of objects) {
+ for (const key in object.properties) {
+ if (Object.prototype.hasOwnProperty.call(properties, key))
continue;
+ const parts = [];
+ for (const other of objects) {
+ const part = other.properties?.[key] ?? undeclaredConstraint(other);
+ if (part === null || part === undefined)
+ continue;
+ if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))
+ parts.push(part);
}
+ const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
+ assignProp(properties, key, merged);
}
+ for (const key of object.required ?? [])
+ required.add(key);
}
+ const folded = { type: "object", properties };
+ if (required.size)
+ folded.required = [...required];
+ if (objects.every((object) => object.additionalProperties === false)) {
+ folded.additionalProperties = false;
+ } else {
+ const constraints = [];
+ for (const object of objects) {
+ const constraint = undeclaredConstraint(object);
+ if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
+ constraints.push(constraint);
+ }
+ if (constraints.length === 1)
+ folded.additionalProperties = constraints[0];
+ else if (constraints.length > 1)
+ folded.additionalProperties = { allOf: constraints };
+ }
+ return folded;
+}
+function foldIntersection(json) {
+ const allOf = json.allOf;
+ if (!Array.isArray(allOf) || allOf.length < 2)
+ return;
+ for (const key of FOLDABLE_KEYS)
+ if (key in json)
+ return;
+ const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));
+ let folded = null;
+ if (!unions.length) {
+ folded = foldObjects(allOf);
+ } else {
+ const union = unions[0];
+ const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));
+ if (Object.keys(union).length !== 1)
+ return;
+ const rest = allOf.filter((m) => m !== union);
+ const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));
+ if (branches.some((b) => !b))
+ return;
+ folded = { [keyword]: branches };
+ }
+ if (!folded)
+ return;
+ delete json.allOf;
+ assignProps(json, folded);
}
function finalize(ctx, schema) {
const root = ctx.seen.get(schema);
@@ -71032,9 +71969,9 @@ function finalize(ctx, schema) {
schema.allOf = schema.allOf ?? [];
schema.allOf.push(refSchema);
} else {
- Object.assign(schema, refSchema);
+ assignProps(schema, refSchema);
}
- Object.assign(schema, _cached);
+ assignProps(schema, _cached);
const isParentRef = zodSchema._zod.parent === ref;
if (isParentRef) {
for (const key in schema) {
@@ -71078,8 +72015,36 @@ function finalize(ctx, schema) {
path: seen.path ?? []
});
};
- for (const entry of [...ctx.seen.entries()].reverse()) {
- flattenRef(entry[0]);
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
+ for (const entry of [...ctx.seen.entries()].reverse()) {
+ flattenRef(entry[0]);
+ }
+ if (ctx.target !== "openapi-3.0") {
+ for (const entry of ctx.seen.entries()) {
+ compactTypeUnion(entry[1].def ?? entry[1].schema);
+ }
+ }
+ for (const rewrite of ctx.deferred)
+ rewrite();
+ if (ctx.intersections.length) {
+ const carriers = new Map;
+ for (const seen of ctx.seen.values()) {
+ for (const json of [seen.schema, seen.def]) {
+ const allOf = json?.allOf;
+ if (!Array.isArray(allOf))
+ continue;
+ const existing = carriers.get(allOf);
+ if (existing)
+ existing.push(json);
+ else
+ carriers.set(allOf, [json]);
+ }
+ }
+ for (const allOf of ctx.intersections) {
+ for (const json of carriers.get(allOf) ?? [])
+ foldIntersection(json);
+ }
+ }
}
const result = {};
if (ctx.target === "draft-2020-12") {
@@ -71095,19 +72060,23 @@ function finalize(ctx, schema) {
throw new Error("Schema is missing an `id` property");
result.$id = ctx.external.uri(id);
}
- Object.assign(result, root.def ?? root.schema);
+ assignProps(result, root.defId ? root.schema : root.def ?? root.schema);
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
if (rootMetaId !== undefined && result.id === rootMetaId)
delete result.id;
const defs = ctx.external?.defs ?? {};
- for (const entry of ctx.seen.entries()) {
- const seen = entry[1];
- if (seen.def && seen.defId) {
- if (seen.def.id === seen.defId)
- delete seen.def.id;
- defs[seen.defId] = seen.def;
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
+ for (const entry of ctx.seen.entries()) {
+ const seen = entry[1];
+ if (seen.def && seen.defId) {
+ if (seen.def.id === seen.defId)
+ delete seen.def.id;
+ assignProp(defs, seen.defId, seen.def);
+ }
}
}
+ if (ctx.external)
+ ctx.sharedEmitDoneFor = ctx.external;
if (ctx.external) {} else {
if (Object.keys(defs).length > 0) {
if (ctx.target === "draft-2020-12") {
@@ -71149,7 +72118,7 @@ function isTransforming(_schema, _ctx) {
return isTransforming(def.valueType, ctx);
if (def.type === "lazy")
return isTransforming(def.getter(), ctx);
- if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") {
return isTransforming(def.innerType, ctx);
}
if (def.type === "intersection") {
@@ -71188,27 +72157,170 @@ function isTransforming(_schema, _ctx) {
}
return false;
}
-var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
+var FOLDABLE_KEYS, UNION_KEYS, createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
const ctx = initializeContext({ ...params, processors });
- process3(schema, ctx);
+ processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
}, createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
const { libraryOptions, target } = params ?? {};
const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
- process3(schema, ctx);
+ processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
var init_to_json_schema = __esm(() => {
init_registries();
+ init_util();
+ FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]);
+ UNION_KEYS = ["oneOf", "anyOf"];
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema-processors.js
-var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema-processors.js
+function aggregateChecks(schema) {
+ const agg = {};
+ const def = schema._zod.def;
+ const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
+ for (const ch of list)
+ contributors[ch._zod.def.check]?.(agg, ch._zod.def);
+ const bag = schema._zod.bag;
+ if (bag.minimum !== undefined)
+ narrowMin(agg, "minimum", bag.minimum);
+ if (bag.exclusiveMinimum !== undefined)
+ narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
+ if (bag.maximum !== undefined)
+ narrowMax(agg, "maximum", bag.maximum);
+ if (bag.exclusiveMaximum !== undefined)
+ narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
+ if (bag.multipleOf !== undefined)
+ addDivisor(agg, bag.multipleOf);
+ if (bag.format !== undefined) {
+ agg.format ?? (agg.format = bag.format);
+ if (bag.format.includes("int"))
+ agg.isInt = true;
+ }
+ if (bag.mime)
+ intersectMime(agg, bag.mime);
+ for (const pattern of bag.patterns ?? [])
+ addPattern(agg, pattern);
+ return agg;
+}
+function inputOptin(schema) {
+ const def = schema._zod.def;
+ if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) {
+ return inputOptin(def.out);
+ }
+ if (def.type === "catch") {
+ return inputOptin(def.innerType);
+ }
+ return schema._zod.optin;
+}
+function stringifyKeyNames(bySchema, json, visited) {
+ if (json.$ref) {
+ if (visited.has(json))
+ return json;
+ visited.add(json);
+ const def = bySchema.get(json)?.def;
+ if (!def)
+ return json;
+ const inlined = stringifyKeyNames(bySchema, def, visited);
+ return inlined === def ? json : inlined;
+ }
+ for (const keyword of ["anyOf", "oneOf"]) {
+ const branches = json[keyword];
+ if (!Array.isArray(branches))
+ continue;
+ const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
+ if (mapped.some((branch, i) => branch !== branches[i]))
+ json = { ...json, [keyword]: mapped };
+ }
+ const types = Array.isArray(json.type) ? json.type : [json.type];
+ const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
+ const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);
+ if (!numericType && !values?.some((v) => typeof v === "number"))
+ return json;
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
+ if (rest.enum)
+ rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
+ else if (typeof rest.const === "number")
+ rest.const = String(rest.const);
+ if (!numericType)
+ return rest;
+ rest.type = "string";
+ if (!values)
+ rest.pattern = (types.includes("number") ? number : integer).source;
+ return rest;
+}
+function rewriteKeyNames(ctx) {
+ const bySchema = new Map;
+ for (const entry of ctx.seen.values()) {
+ if (entry.def && !bySchema.has(entry.schema))
+ bySchema.set(entry.schema, entry);
+ }
+ const rewrites = new Map;
+ for (const record of pendingRecords.get(ctx) ?? []) {
+ const seen = ctx.seen.get(record);
+ const names = (seen?.def ?? seen?.schema)?.propertyNames;
+ if (!names || names === true || rewrites.has(names))
+ continue;
+ const rewritten = stringifyKeyNames(bySchema, names, new Set);
+ if (rewritten !== names)
+ rewrites.set(names, rewritten);
+ }
+ if (!rewrites.size)
+ return;
+ for (const entry of ctx.seen.values()) {
+ for (const carrier of [entry.schema, entry.def]) {
+ const rewritten = carrier && rewrites.get(carrier.propertyNames);
+ if (rewritten)
+ carrier.propertyNames = rewritten;
+ }
+ }
+}
+function serializeDefaultValue(value, schema, ctx, json, params) {
+ let unrepresentable = false;
+ const serialized = JSON.stringify(value, (_, val) => {
+ if (typeof val !== "bigint")
+ return val;
+ unrepresentable = true;
+ return null;
+ });
+ if (!unrepresentable)
+ return JSON.parse(serialized);
+ handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
+ return UNREPRESENTABLE_DEFAULT;
+}
+var narrowMin = (agg, key, value) => {
+ if (agg[key] === undefined || value > agg[key])
+ agg[key] = value;
+}, narrowMax = (agg, key, value) => {
+ if (agg[key] === undefined || value < agg[key])
+ agg[key] = value;
+}, narrowBoth = (agg, value) => {
+ narrowMin(agg, "minimum", value);
+ narrowMax(agg, "maximum", value);
+}, addDivisor = (agg, value) => {
+ agg.multipleOf ?? (agg.multipleOf = []);
+ if (!agg.multipleOf.includes(value))
+ agg.multipleOf.push(value);
+}, addPattern = (agg, pattern) => {
+ agg.patterns ?? (agg.patterns = new Set);
+ agg.patterns.add(pattern);
+}, intersectMime = (agg, mime) => {
+ agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
+}, setFormat = (agg, format) => {
+ agg.format = format;
+ if (format.includes("int"))
+ agg.isInt = true;
+}, minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum), maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum), formatContributor = (ranges) => (agg, def) => {
+ setFormat(agg, def.format);
+ const [minimum, maximum] = ranges[def.format];
+ narrowMin(agg, "minimum", minimum);
+ narrowMax(agg, "maximum", maximum);
+}, contributors, formatMap, exactPatterns, exactPattern = (p) => exactPatterns.get(p) ?? p, stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
- const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minLength = minimum;
if (typeof maximum === "number")
@@ -71217,32 +72329,29 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
json.format = formatMap[format] ?? format;
if (json.format === "")
delete json.format;
- if (format === "time") {
+ if (format === "time" || laxFormat) {
delete json.format;
}
}
if (contentEncoding)
json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
- const regexes = [...patterns];
- if (regexes.length === 1)
- json.pattern = regexes[0].source;
- else if (regexes.length > 1) {
+ const patternList = [...patterns].map(exactPattern);
+ if (patternList.length === 1)
+ json.pattern = patternList[0].source;
+ else if (patternList.length > 1) {
json.allOf = [
- ...regexes.map((regex) => ({
+ ...patternList.map((regex) => ({
...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
pattern: regex.source
}))
];
}
}
-}, numberProcessor = (schema, ctx, _json, _params) => {
+}, numberProcessor = (schema, ctx, _json, params) => {
const json = _json;
- const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
- if (typeof format === "string" && format.includes("int"))
- json.type = "integer";
- else
- json.type = "number";
+ const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
+ json.type = isInt ? "integer" : "number";
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
@@ -71266,8 +72375,20 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
} else if (typeof maximum === "number") {
json.maximum = maximum;
}
- if (typeof multipleOf === "number")
- json.multipleOf = multipleOf;
+ if (multipleOf) {
+ const divisors = new Set;
+ for (const divisor of multipleOf) {
+ if (Number.isFinite(divisor) && divisor !== 0)
+ divisors.add(Math.abs(divisor));
+ else
+ handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
+ }
+ const [first, ...rest] = divisors;
+ if (first !== undefined)
+ json.multipleOf = first;
+ if (rest.length)
+ json.allOf = [...json.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
+ }
}, booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
}, neverProcessor = (_schema, _ctx, json, _params) => {
@@ -71275,25 +72396,30 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}, unknownProcessor = (_schema, _ctx, _json, _params) => {}, enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = getEnumValues(def.entries);
+ if (values.length === 0) {
+ json.not = {};
+ return;
+ }
if (values.every((v) => typeof v === "number"))
json.type = "number";
if (values.every((v) => typeof v === "string"))
json.type = "string";
json.enum = values;
-}, literalProcessor = (schema, ctx, json, _params) => {
+}, literalProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
+ if (def.values.length === 0) {
+ json.not = {};
+ return;
+ }
const vals = [];
for (const val of def.values) {
if (val === undefined) {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Literal `undefined` cannot be represented in JSON Schema");
- }
+ if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema"))
+ return;
} else if (typeof val === "bigint") {
- if (ctx.unrepresentable === "throw") {
- throw new Error("BigInt literals cannot be represented in JSON Schema");
- } else {
- vals.push(Number(val));
- }
+ if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema"))
+ return;
+ vals.push(Number(val));
} else {
vals.push(val);
}
@@ -71317,50 +72443,48 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
json.type = "null";
json.enum = vals;
}
-}, customProcessor = (_schema, ctx, _json, _params) => {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Custom types cannot be represented in JSON Schema");
- }
-}, transformProcessor = (_schema, ctx, _json, _params) => {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Transforms cannot be represented in JSON Schema");
- }
+}, customProcessor = (schema, ctx, json, params) => {
+ handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
+}, transformProcessor = (schema, ctx, json, params) => {
+ handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
}, arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
- const { minimum, maximum } = schema._zod.bag;
+ const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
- json.items = process3(def.element, ctx, {
+ json.items = processSchema(def.element, ctx, {
...params,
path: [...params.path, "items"]
});
}, objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
+ const shape = def.shape;
+ const symbolKeys = Object.getOwnPropertySymbols(shape);
+ if (symbolKeys.length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) {
+ return;
+ }
json.type = "object";
json.properties = {};
- const shape = def.shape;
for (const key in shape) {
- json.properties[key] = process3(shape[key], ctx, {
+ assignProp(json.properties, key, processSchema(shape[key], ctx, {
...params,
path: [...params.path, "properties", key]
- });
+ }));
}
- const allKeys = new Set(Object.keys(shape));
- const requiredKeys = new Set([...allKeys].filter((key) => {
- const v = def.shape[key]._zod;
- if (ctx.io === "input") {
- return v.optin === undefined;
- } else {
- return v.optout === undefined;
+ const requiredKeys = [];
+ for (const key of Object.keys(shape)) {
+ const field = def.shape[key];
+ if (ctx.io === "input" ? inputOptin(field) === undefined : field._zod.optout === undefined) {
+ requiredKeys.push(key);
}
- }));
- if (requiredKeys.size > 0) {
- json.required = Array.from(requiredKeys);
+ }
+ if (requiredKeys.length > 0) {
+ json.required = requiredKeys;
}
if (def.catchall?._zod.def.type === "never") {
json.additionalProperties = false;
@@ -71368,7 +72492,7 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
if (ctx.io === "output")
json.additionalProperties = false;
} else if (def.catchall) {
- json.additionalProperties = process3(def.catchall, ctx, {
+ json.additionalProperties = processSchema(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
@@ -71376,7 +72500,7 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}, unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const isExclusive = def.inclusive === false;
- const options = def.options.map((x, i) => process3(x, ctx, {
+ const options = def.options.map((x, i) => processSchema(x, ctx, {
...params,
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
}));
@@ -71387,11 +72511,11 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}
}, intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- const a = process3(def.left, ctx, {
+ const a = processSchema(def.left, ctx, {
...params,
path: [...params.path, "allOf", 0]
});
- const b = process3(def.right, ctx, {
+ const b = processSchema(def.right, ctx, {
...params,
path: [...params.path, "allOf", 1]
});
@@ -71401,44 +72525,52 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
...isSimpleIntersection(b) ? b.allOf : [b]
];
json.allOf = allOf;
-}, recordProcessor = (schema, ctx, _json, params) => {
+ ctx.intersections.push(allOf);
+}, pendingRecords, recordProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "object";
const keyType = def.keyType;
- const keyBag = keyType._zod.bag;
- const patterns = keyBag?.patterns;
+ const patterns = aggregateChecks(keyType).patterns;
if (def.mode === "loose" && patterns && patterns.size > 0) {
- const valueSchema = process3(def.valueType, ctx, {
+ const valueSchema = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "patternProperties", "*"]
});
json.patternProperties = {};
for (const pattern of patterns) {
- json.patternProperties[pattern.source] = valueSchema;
+ assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
}
} else {
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
- json.propertyNames = process3(def.keyType, ctx, {
+ json.propertyNames = processSchema(def.keyType, ctx, {
...params,
path: [...params.path, "propertyNames"]
});
+ let pending = pendingRecords.get(ctx);
+ if (!pending) {
+ pending = [];
+ pendingRecords.set(ctx, pending);
+ ctx.deferred.push(() => rewriteKeyNames(ctx));
+ }
+ pending.push(schema);
}
- json.additionalProperties = process3(def.valueType, ctx, {
+ json.additionalProperties = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
}
const keyValues = keyType._zod.values;
- if (keyValues) {
+ const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined;
+ if (keyValues && !def.partial && !omittableOnInput) {
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
if (validKeyValues.length > 0) {
- json.required = validKeyValues;
+ json.required = validKeyValues.map(String);
}
}
}, nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- const inner = process3(def.innerType, ctx, params);
+ const inner = processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
@@ -71448,56 +72580,87 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}
}, nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
-}, defaultProcessor = (schema, ctx, json, params) => {
+}, UNREPRESENTABLE_DEFAULT, defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
- json.default = JSON.parse(JSON.stringify(def.defaultValue));
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
+ if (value !== UNREPRESENTABLE_DEFAULT)
+ json.default = value;
}, prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
- if (ctx.io === "input")
- json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
+ if (ctx.io !== "input")
+ return;
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
+ if (value !== UNREPRESENTABLE_DEFAULT)
+ json._prefault = value;
}, catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(undefined);
} catch {
- throw new Error("Dynamic catch values are not supported in JSON Schema");
+ handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
+ return;
}
json.default = catchValue;
}, pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
- process3(innerType, ctx, params);
+ processSchema(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
}, readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
}, optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
var init_json_schema_processors = __esm(() => {
+ init_regexes();
+ init_schemas();
init_to_json_schema();
init_util();
+ contributors = {
+ greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
+ less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
+ multiple_of: (agg, def) => addDivisor(agg, def.value),
+ number_format: formatContributor(NUMBER_FORMAT_RANGES),
+ bigint_format: formatContributor(BIGINT_FORMAT_RANGES),
+ min_length: minContributor,
+ max_length: maxContributor,
+ length_equals: (agg, def) => narrowBoth(agg, def.length),
+ min_size: minContributor,
+ max_size: maxContributor,
+ size_equals: (agg, def) => narrowBoth(agg, def.size),
+ string_format: (agg, def) => {
+ setFormat(agg, def.format);
+ if (def.pattern)
+ addPattern(agg, def.pattern);
+ if (def.format === "base64" || def.format === "base64url")
+ agg.contentEncoding = def.format;
+ if (def.local || def.precision === -1)
+ agg.laxFormat = true;
+ },
+ mime_type: (agg, def) => intersectMime(agg, def.mime)
+ };
formatMap = {
guid: "uuid",
url: "uri",
@@ -71505,12 +72668,18 @@ var init_json_schema_processors = __esm(() => {
json_string: "json-string",
regex: ""
};
+ exactPatterns = new Map([
+ [base64Charset, base64],
+ [base64urlCharset, base64url]
+ ]);
+ pendingRecords = new WeakMap;
+ UNREPRESENTABLE_DEFAULT = Symbol();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema.js
var init_json_schema = () => {};
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/index.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/index.js
var init_core2 = __esm(() => {
init_util();
init_regexes();
@@ -71520,80 +72689,57 @@ var init_core2 = __esm(() => {
init_parse();
init_errors();
init_schemas();
+ init_memoizer();
init_checks();
init_versions();
init_registries();
+ init_compile();
init_api();
init_to_json_schema();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/checks.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/checks.js
var init_checks2 = __esm(() => {
init_core2();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/iso.js
-function datetime2(params) {
- return _isoDateTime(ZodISODateTime, params);
-}
-function date2(params) {
- return _isoDate(ZodISODate, params);
-}
-function time2(params) {
- return _isoTime(ZodISOTime, params);
-}
-function duration2(params) {
- return _isoDuration(ZodISODuration, params);
-}
-var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration;
-var init_iso = __esm(() => {
- init_core2();
- init_schemas2();
- ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
- $ZodISODateTime.init(inst, def);
- ZodStringFormat.init(inst, def);
- });
- ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
- $ZodISODate.init(inst, def);
- ZodStringFormat.init(inst, def);
- });
- ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
- $ZodISOTime.init(inst, def);
- ZodStringFormat.init(inst, def);
- });
- ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
- $ZodISODuration.init(inst, def);
- ZodStringFormat.init(inst, def);
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/errors.js
+function _lazyMethod(proto, key, make) {
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const value = make(this);
+ Object.defineProperty(this, key, { value, configurable: true, writable: true });
+ return value;
+ },
+ set(value) {
+ Object.defineProperty(this, key, { value, configurable: true, writable: true });
+ }
});
-});
-
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/errors.js
-var initializer2 = (inst, issues) => {
+}
+var _installedErrorProtos, initializer2 = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
- Object.defineProperties(inst, {
- format: {
- value: (mapper) => formatError2(inst, mapper)
- },
- flatten: {
- value: (mapper) => flattenError(inst, mapper)
- },
- addIssue: {
- value: (issue) => {
- inst.issues.push(issue);
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
- }
- },
- addIssues: {
- value: (issues) => {
- inst.issues.push(...issues);
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
- }
- },
- isEmpty: {
- get() {
- return inst.issues.length === 0;
- }
+ const proto = Object.getPrototypeOf(inst);
+ if (_installedErrorProtos.has(proto))
+ return;
+ _installedErrorProtos.add(proto);
+ _lazyMethod(proto, "format", (self) => (mapper) => formatError2(self, mapper));
+ _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper));
+ _lazyMethod(proto, "addIssue", (self) => (issue) => {
+ self.issues.push(issue);
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
+ });
+ _lazyMethod(proto, "addIssues", (self) => (issues) => {
+ self.issues.push(...issues);
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
+ });
+ Object.defineProperty(proto, "isEmpty", {
+ configurable: true,
+ enumerable: false,
+ get() {
+ return this.issues.length === 0;
}
});
}, ZodRealError;
@@ -71601,20 +72747,22 @@ var init_errors2 = __esm(() => {
init_core2();
init_core2();
init_util();
- ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
+ _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
+ ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, undefined, {
Parent: Error
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/parse.js
-var parse5, parseAsync2, safeParse2, safeParseAsync2, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync;
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/parse.js
+var parse4, parseAsync, safeParse, safeParseAsync, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync;
var init_parse2 = __esm(() => {
init_core2();
init_errors2();
- parse5 = /* @__PURE__ */ _parse(ZodRealError);
- parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
- safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
- safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
+ init_core2();
+ parse4 = /* @__PURE__ */ _parse(ZodRealError);
+ parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
+ safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
+ safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
encode = /* @__PURE__ */ _encode(ZodRealError);
decode = /* @__PURE__ */ _decode(ZodRealError);
encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
@@ -71625,42 +72773,14 @@ var init_parse2 = __esm(() => {
safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/schemas.js
-function _installLazyMethods(inst, group, methods) {
- const proto = Object.getPrototypeOf(inst);
- let installed = _installedGroups.get(proto);
- if (!installed) {
- installed = new Set;
- _installedGroups.set(proto, installed);
- }
- if (installed.has(group))
- return;
- installed.add(group);
- for (const key in methods) {
- const fn = methods[key];
- Object.defineProperty(proto, key, {
- configurable: true,
- enumerable: false,
- get() {
- const bound = fn.bind(this);
- Object.defineProperty(this, key, {
- configurable: true,
- writable: true,
- enumerable: true,
- value: bound
- });
- return bound;
- },
- set(v) {
- Object.defineProperty(this, key, {
- configurable: true,
- writable: true,
- enumerable: true,
- value: v
- });
- }
- });
- }
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/schemas.js
+function _ensureDefaultLocale() {
+ if (!globalConfig.localeError)
+ config(en_default());
+}
+function _ensureDefaultMemoizer() {
+ if (!globalConfig.memoizer)
+ config({ memoizer: memoizer() });
}
function string2(params) {
return _string(ZodString, params);
@@ -71797,7 +72917,7 @@ function _catch(innerType, catchValue) {
return new ZodCatch({
type: "catch",
innerType,
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
+ catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
});
}
function pipe(in_, out) {
@@ -71826,236 +72946,344 @@ function preprocess(fn, schema) {
out: schema
});
}
-var _installedGroups, ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber, ZodNumberFormat, ZodBoolean, ZodUnknown, ZodNever, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodRecord, ZodEnum, ZodLiteral, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodCatch, ZodPipe, ZodPreprocess, ZodReadonly, ZodCustom;
+var ZodType, _ZodString, ZodString, ZodStringFormat, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber, ZodNumberFormat, ZodBoolean, ZodUnknown, ZodNever, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodRecord, ZodEnum, ZodLiteral, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodCatch, ZodPipe, ZodPreprocess, ZodReadonly, ZodCustom;
var init_schemas2 = __esm(() => {
init_core2();
init_core2();
init_json_schema_processors();
init_to_json_schema();
+ init_en();
init_checks2();
- init_iso();
init_parse2();
- _installedGroups = /* @__PURE__ */ new WeakMap;
ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
+ _ensureDefaultLocale();
$ZodType.init(inst, def);
- Object.assign(inst["~standard"], {
- jsonSchema: {
- input: createStandardJSONSchemaMethod(inst, "input"),
- output: createStandardJSONSchemaMethod(inst, "output")
- }
- });
- inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
inst.def = def;
inst.type = def.type;
- Object.defineProperty(inst, "_def", { value: def });
- inst.parse = (data, params) => parse5(inst, data, params, { callee: inst.parse });
- inst.safeParse = (data, params) => safeParse2(inst, data, params);
- inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
- inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
- inst.spa = inst.safeParseAsync;
- inst.encode = (data, params) => encode(inst, data, params);
- inst.decode = (data, params) => decode(inst, data, params);
- inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
- inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
- inst.safeEncode = (data, params) => safeEncode(inst, data, params);
- inst.safeDecode = (data, params) => safeDecode(inst, data, params);
- inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
- inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
- _installLazyMethods(inst, "ZodType", {
- check(...chks) {
- const def = this.def;
- return this.clone(mergeDefs(def, {
- checks: [
- ...def.checks ?? [],
- ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
- ]
- }), { parent: true });
- },
- with(...chks) {
- return this.check(...chks);
- },
- clone(def, params) {
- return clone(this, def, params);
- },
- brand() {
- return this;
- },
- register(reg, meta) {
- reg.add(this, meta);
- return this;
- },
- refine(check, params) {
- return this.check(refine(check, params));
- },
- superRefine(refinement, params) {
- return this.check(superRefine(refinement, params));
- },
- overwrite(fn) {
- return this.check(_overwrite(fn));
- },
- optional() {
- return optional(this);
- },
- exactOptional() {
- return exactOptional(this);
- },
- nullable() {
- return nullable(this);
- },
- nullish() {
- return optional(nullable(this));
- },
- nonoptional(params) {
- return nonoptional(this, params);
- },
- array() {
- return array(this);
- },
- or(arg) {
- return union([this, arg]);
- },
- and(arg) {
- return intersection(this, arg);
- },
- transform(tx) {
- return pipe(this, transform(tx));
- },
- default(d) {
- return _default(this, d);
- },
- prefault(d) {
- return prefault(this, d);
- },
- catch(params) {
- return _catch(this, params);
- },
- pipe(target) {
- return pipe(this, target);
- },
- readonly() {
- return readonly(this);
- },
- describe(description) {
- const cl = this.clone();
- globalRegistry.add(cl, { description });
- return cl;
- },
- meta(...args) {
- if (args.length === 0)
- return globalRegistry.get(this);
- const cl = this.clone();
- globalRegistry.add(cl, args[0]);
- return cl;
- },
- isOptional() {
- return this.safeParse(undefined).success;
- },
- isNullable() {
- return this.safeParse(null).success;
- },
- apply(fn) {
- return fn(this);
- }
- });
- Object.defineProperty(inst, "description", {
- get() {
- return globalRegistry.get(inst)?.description;
- },
- configurable: true
- });
return inst;
+ }, {
+ check(...chks) {
+ const def = this.def;
+ return this.clone(mergeDefs(def, {
+ checks: [
+ ...def.checks ?? [],
+ ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
+ ]
+ }), { parent: true });
+ },
+ with(...chks) {
+ return this.check(...chks);
+ },
+ clone(def, params) {
+ return clone(this, def, params);
+ },
+ brand() {
+ return this;
+ },
+ register(reg, meta) {
+ reg.add(this, meta);
+ return this;
+ },
+ refine(check, params) {
+ return this.check(refine(check, params));
+ },
+ superRefine(refinement, params) {
+ return this.check(superRefine(refinement, params));
+ },
+ overwrite(fn) {
+ return this.check(_overwrite(fn));
+ },
+ optional() {
+ return optional(this);
+ },
+ exactOptional() {
+ return exactOptional(this);
+ },
+ nullable() {
+ return nullable(this);
+ },
+ nullish() {
+ return optional(nullable(this));
+ },
+ nonoptional(params) {
+ return nonoptional(this, params);
+ },
+ array() {
+ return array(this);
+ },
+ or(arg) {
+ return union([this, arg]);
+ },
+ and(arg) {
+ return intersection(this, arg);
+ },
+ transform(tx) {
+ return pipe(this, transform(tx));
+ },
+ default(d) {
+ return _default(this, d);
+ },
+ prefault(d) {
+ return prefault(this, d);
+ },
+ catch(params) {
+ return _catch(this, params);
+ },
+ pipe(target) {
+ return pipe(this, target);
+ },
+ readonly() {
+ return readonly(this);
+ },
+ describe(description) {
+ const cl = this.clone();
+ globalRegistry.add(cl, { description });
+ return cl;
+ },
+ meta(...args) {
+ if (args.length === 0)
+ return globalRegistry.get(this);
+ const cl = this.clone();
+ globalRegistry.add(cl, args[0]);
+ return cl;
+ },
+ isOptional() {
+ return this.safeParse(undefined).success;
+ },
+ isNullable() {
+ return this.safeParse(null).success;
+ },
+ apply(fn, ...args) {
+ return args.length === 0 ? fn(this) : fn(this, ...args);
+ },
+ get "~standard"() {
+ return hide(this, "~standard", {
+ ...standardProps(this),
+ jsonSchema: {
+ input: createStandardJSONSchemaMethod(this, "input"),
+ output: createStandardJSONSchemaMethod(this, "output")
+ }
+ });
+ },
+ set "~standard"(value) {
+ own(this, "~standard", value);
+ },
+ parse: function _parse(data, params) {
+ return parse4(this, data, params, { callee: _parse });
+ },
+ parseAsync: async function _parseAsync(data, params) {
+ return await parseAsync(this, data, params, { callee: _parseAsync });
+ },
+ safeParse(data, params) {
+ return safeParse(this, data, params);
+ },
+ async safeParseAsync(data, params) {
+ return safeParseAsync(this, data, params);
+ },
+ get spa() {
+ return this?.safeParseAsync;
+ },
+ set spa(value) {
+ own(this, "spa", value);
+ },
+ validate(data, params) {
+ return validate(this, data, params);
+ },
+ validateAsync(data, params) {
+ return validateAsync(this, data, params);
+ },
+ encode: function _encode(data, params) {
+ return encode(this, data, params, { callee: _encode });
+ },
+ decode: function _decode(data, params) {
+ return decode(this, data, params, { callee: _decode });
+ },
+ encodeAsync: async function _encodeAsync(data, params) {
+ return await encodeAsync(this, data, params, { callee: _encodeAsync });
+ },
+ decodeAsync: async function _decodeAsync(data, params) {
+ return await decodeAsync(this, data, params, { callee: _decodeAsync });
+ },
+ safeEncode(data, params) {
+ return safeEncode(this, data, params);
+ },
+ safeDecode(data, params) {
+ return safeDecode(this, data, params);
+ },
+ async safeEncodeAsync(data, params) {
+ return safeEncodeAsync(this, data, params);
+ },
+ async safeDecodeAsync(data, params) {
+ return safeDecodeAsync(this, data, params);
+ },
+ toJSONSchema(params) {
+ return createToJSONSchemaMethod(this, {})(params);
+ },
+ get description() {
+ return globalRegistry.get(this)?.description;
+ },
+ get _def() {
+ return this._zod.def;
+ }
});
_ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
- const bag = inst._zod.bag;
- inst.format = bag.format ?? null;
- inst.minLength = bag.minimum ?? null;
- inst.maxLength = bag.maximum ?? null;
- _installLazyMethods(inst, "_ZodString", {
- regex(...args) {
- return this.check(_regex(...args));
- },
- includes(...args) {
- return this.check(_includes(...args));
- },
- startsWith(...args) {
- return this.check(_startsWith(...args));
- },
- endsWith(...args) {
- return this.check(_endsWith(...args));
- },
- min(...args) {
- return this.check(_minLength(...args));
- },
- max(...args) {
- return this.check(_maxLength(...args));
- },
- length(...args) {
- return this.check(_length(...args));
- },
- nonempty(...args) {
- return this.check(_minLength(1, ...args));
- },
- lowercase(params) {
- return this.check(_lowercase(params));
- },
- uppercase(params) {
- return this.check(_uppercase(params));
- },
- trim() {
- return this.check(_trim());
- },
- normalize(...args) {
- return this.check(_normalize(...args));
- },
- toLowerCase() {
- return this.check(_toLowerCase());
- },
- toUpperCase() {
- return this.check(_toUpperCase());
- },
- slugify() {
- return this.check(_slugify());
- }
- });
- });
+ }, /* @__PURE__ */ derived({
+ format: (inst) => aggregateChecks(inst).format ?? null,
+ minLength: (inst) => aggregateChecks(inst).minimum ?? null,
+ maxLength: (inst) => aggregateChecks(inst).maximum ?? null
+ }, {
+ regex(...args) {
+ return this.check(_regex(...args));
+ },
+ includes(...args) {
+ return this.check(_includes(...args));
+ },
+ startsWith(...args) {
+ return this.check(_startsWith(...args));
+ },
+ endsWith(...args) {
+ return this.check(_endsWith(...args));
+ },
+ min(...args) {
+ return this.check(_minLength(...args));
+ },
+ max(...args) {
+ return this.check(_maxLength(...args));
+ },
+ length(...args) {
+ return this.check(_length(...args));
+ },
+ nonempty(...args) {
+ return this.check(_minLength(1, ...args));
+ },
+ lowercase(params) {
+ return this.check(_lowercase(params));
+ },
+ uppercase(params) {
+ return this.check(_uppercase(params));
+ },
+ trim() {
+ return this.check(_trim());
+ },
+ normalize(...args) {
+ return this.check(_normalize(...args));
+ },
+ toLowerCase() {
+ return this.check(_toLowerCase());
+ },
+ toUpperCase() {
+ return this.check(_toUpperCase());
+ },
+ slugify() {
+ return this.check(_slugify());
+ }
+ }));
ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
$ZodString.init(inst, def);
_ZodString.init(inst, def);
- inst.email = (params) => inst.check(_email(ZodEmail, params));
- inst.url = (params) => inst.check(_url(ZodURL, params));
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
- inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
- inst.datetime = (params) => inst.check(datetime2(params));
- inst.date = (params) => inst.check(date2(params));
- inst.time = (params) => inst.check(time2(params));
- inst.duration = (params) => inst.check(duration2(params));
+ }, {
+ email(params) {
+ return this.check(_email(ZodEmail, params));
+ },
+ url(params) {
+ return this.check(_url(ZodURL, params));
+ },
+ jwt(params) {
+ return this.check(_jwt(ZodJWT, params));
+ },
+ emoji(params) {
+ return this.check(_emoji2(ZodEmoji, params));
+ },
+ guid(params) {
+ return this.check(_guid(ZodGUID, params));
+ },
+ uuid(params) {
+ return this.check(_uuid(ZodUUID, params));
+ },
+ uuidv4(params) {
+ return this.check(_uuidv4(ZodUUID, params));
+ },
+ uuidv6(params) {
+ return this.check(_uuidv6(ZodUUID, params));
+ },
+ uuidv7(params) {
+ return this.check(_uuidv7(ZodUUID, params));
+ },
+ nanoid(params) {
+ return this.check(_nanoid(ZodNanoID, params));
+ },
+ cuid(params) {
+ return this.check(_cuid(ZodCUID, params));
+ },
+ cuid2(params) {
+ return this.check(_cuid2(ZodCUID2, params));
+ },
+ ulid(params) {
+ return this.check(_ulid(ZodULID, params));
+ },
+ base64(params) {
+ return this.check(_base64(ZodBase64, params));
+ },
+ base64url(params) {
+ return this.check(_base64url(ZodBase64URL, params));
+ },
+ xid(params) {
+ return this.check(_xid(ZodXID, params));
+ },
+ ksuid(params) {
+ return this.check(_ksuid(ZodKSUID, params));
+ },
+ ipv4(params) {
+ return this.check(_ipv4(ZodIPv4, params));
+ },
+ ipv6(params) {
+ return this.check(_ipv6(ZodIPv6, params));
+ },
+ cidrv4(params) {
+ return this.check(_cidrv4(ZodCIDRv4, params));
+ },
+ cidrv6(params) {
+ return this.check(_cidrv6(ZodCIDRv6, params));
+ },
+ e164(params) {
+ return this.check(_e164(ZodE164, params));
+ },
+ datetime(params) {
+ return this.check(_isoDateTime(ZodISODateTime, params));
+ },
+ date(params) {
+ return this.check(_isoDate(ZodISODate, params));
+ },
+ time(params) {
+ return this.check(_isoTime(ZodISOTime, params));
+ },
+ duration(params) {
+ return this.check(_isoDuration(ZodISODuration, params));
+ }
});
ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
+ ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
+ $ZodISODateTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
+ ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
+ $ZodISODate.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
+ ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
+ $ZodISOTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
+ ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
+ $ZodISODuration.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
@@ -72136,60 +73364,68 @@ var init_schemas2 = __esm(() => {
$ZodNumber.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
- _installLazyMethods(inst, "ZodNumber", {
- gt(value, params) {
- return this.check(_gt(value, params));
- },
- gte(value, params) {
- return this.check(_gte(value, params));
- },
- min(value, params) {
- return this.check(_gte(value, params));
- },
- lt(value, params) {
- return this.check(_lt(value, params));
- },
- lte(value, params) {
- return this.check(_lte(value, params));
- },
- max(value, params) {
- return this.check(_lte(value, params));
- },
- int(params) {
- return this.check(int(params));
- },
- safe(params) {
- return this.check(int(params));
- },
- positive(params) {
- return this.check(_gt(0, params));
- },
- nonnegative(params) {
- return this.check(_gte(0, params));
- },
- negative(params) {
- return this.check(_lt(0, params));
- },
- nonpositive(params) {
- return this.check(_lte(0, params));
- },
- multipleOf(value, params) {
- return this.check(_multipleOf(value, params));
- },
- step(value, params) {
- return this.check(_multipleOf(value, params));
- },
- finite() {
- return this;
- }
- });
- const bag = inst._zod.bag;
- inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
- inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
- inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
inst.isFinite = true;
- inst.format = bag.format ?? null;
- });
+ }, /* @__PURE__ */ derived({
+ minValue: (inst) => {
+ const { minimum, exclusiveMinimum } = aggregateChecks(inst);
+ return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);
+ },
+ maxValue: (inst) => {
+ const { maximum, exclusiveMaximum } = aggregateChecks(inst);
+ return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);
+ },
+ isInt: (inst) => {
+ const { isInt, multipleOf } = aggregateChecks(inst);
+ return !!isInt || !!multipleOf?.some(Number.isSafeInteger);
+ },
+ format: (inst) => aggregateChecks(inst).format ?? null
+ }, {
+ gt(value, params) {
+ return this.check(_gt(value, params));
+ },
+ gte(value, params) {
+ return this.check(_gte(value, params));
+ },
+ min(value, params) {
+ return this.check(_gte(value, params));
+ },
+ lt(value, params) {
+ return this.check(_lt(value, params));
+ },
+ lte(value, params) {
+ return this.check(_lte(value, params));
+ },
+ max(value, params) {
+ return this.check(_lte(value, params));
+ },
+ int(params) {
+ return this.check(int(params));
+ },
+ safe(params) {
+ return this.check(int(params));
+ },
+ positive(params) {
+ return this.check(_gt(0, params));
+ },
+ nonnegative(params) {
+ return this.check(_gte(0, params));
+ },
+ negative(params) {
+ return this.check(_lt(0, params));
+ },
+ nonpositive(params) {
+ return this.check(_lte(0, params));
+ },
+ multipleOf(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ step(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ finite() {
+ return this;
+ }
+ }));
ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
$ZodNumberFormat.init(inst, def);
ZodNumber.init(inst, def);
@@ -72210,76 +73446,77 @@ var init_schemas2 = __esm(() => {
inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
});
ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodArray.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
- _installLazyMethods(inst, "ZodArray", {
- min(n, params) {
- return this.check(_minLength(n, params));
- },
- nonempty(params) {
- return this.check(_minLength(1, params));
- },
- max(n, params) {
- return this.check(_maxLength(n, params));
- },
- length(n, params) {
- return this.check(_length(n, params));
- },
- unwrap() {
- return this.element;
- }
- });
+ }, {
+ min(n, params) {
+ return this.check(_minLength(n, params));
+ },
+ nonempty(params) {
+ return this.check(_minLength(1, params));
+ },
+ max(n, params) {
+ return this.check(_maxLength(n, params));
+ },
+ length(n, params) {
+ return this.check(_length(n, params));
+ },
+ unwrap() {
+ return this.element;
+ }
});
ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodObjectJIT.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
- defineLazy(inst, "shape", () => {
- return def.shape;
- });
- _installLazyMethods(inst, "ZodObject", {
- keyof() {
- return _enum(Object.keys(this._zod.def.shape));
- },
- catchall(catchall) {
- return this.clone({ ...this._zod.def, catchall });
- },
- passthrough() {
- return this.clone({ ...this._zod.def, catchall: unknown() });
- },
- loose() {
- return this.clone({ ...this._zod.def, catchall: unknown() });
- },
- strict() {
- return this.clone({ ...this._zod.def, catchall: never() });
- },
- strip() {
- return this.clone({ ...this._zod.def, catchall: undefined });
- },
- extend(incoming) {
- return extend(this, incoming);
- },
- safeExtend(incoming) {
- return safeExtend(this, incoming);
- },
- merge(other) {
- return merge(this, other);
- },
- pick(mask) {
- return pick3(this, mask);
- },
- omit(mask) {
- return omit(this, mask);
- },
- partial(...args) {
- return partial(ZodOptional, this, args[0]);
- },
- required(...args) {
- return required(ZodNonOptional, this, args[0]);
- }
- });
+ installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
+ }, {
+ keyof() {
+ return _enum(Object.keys(this._zod.def.shape));
+ },
+ catchall(catchall) {
+ return this.clone(mergeDefs(this._zod.def, { catchall }));
+ },
+ passthrough() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
+ },
+ loose() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
+ },
+ strict() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: never() }));
+ },
+ strip() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: undefined }));
+ },
+ extend(incoming) {
+ return extend(this, incoming);
+ },
+ safeExtend(incoming) {
+ return safeExtend(this, incoming);
+ },
+ merge(other) {
+ return merge(this, other);
+ },
+ pick(mask) {
+ return pick3(this, mask);
+ },
+ omit(mask) {
+ return omit(this, mask);
+ },
+ partial(...args) {
+ return partial(ZodOptional, this, args[0]);
+ },
+ exactPartial(...args) {
+ return partial(ZodExactOptional, this, args[0], "exactPartial");
+ },
+ required(...args) {
+ return required(ZodNonOptional, this, args[0]);
+ }
});
ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
$ZodUnion.init(inst, def);
@@ -72297,6 +73534,7 @@ var init_schemas2 = __esm(() => {
inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
});
ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodRecord.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
@@ -72308,7 +73546,7 @@ var init_schemas2 = __esm(() => {
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
inst.enum = def.entries;
- inst.options = Object.values(def.entries);
+ inst.options = [...inst._zod.values];
const keys = new Set(Object.keys(def.entries));
inst.extract = (values, params) => {
const newEntries = {};
@@ -72356,6 +73594,7 @@ var init_schemas2 = __esm(() => {
});
});
ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodTransform.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
@@ -72371,7 +73610,8 @@ var init_schemas2 = __esm(() => {
if (_issue.fatal)
_issue.continue = false;
_issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
+ if (!("input" in _issue))
+ _issue.input = payload.value;
_issue.inst ?? (_issue.inst = inst);
payload.issues.push(issue(_issue));
}
@@ -72380,12 +73620,10 @@ var init_schemas2 = __esm(() => {
if (output instanceof Promise) {
return output.then((output) => {
payload.value = output;
- payload.fallback = true;
return payload;
});
}
payload.value = output;
- payload.fallback = true;
return payload;
};
});
@@ -72457,20 +73695,21 @@ var init_schemas2 = __esm(() => {
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/compat.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/compat.js
var ZodFirstPartyTypeKind;
var init_compat = __esm(() => {
(function(ZodFirstPartyTypeKind) {})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/coerce.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/iso.js
+var init_iso = () => {};
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/coerce.js
var init_coerce = () => {};
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/external.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/external.js
var init_external = __esm(() => {
init_core2();
- init_core2();
- init_en();
init_locales();
init_iso();
init_coerce();
@@ -72479,10 +73718,9 @@ var init_external = __esm(() => {
init_errors2();
init_parse2();
init_compat();
- config(en_default());
});
-// node_modules/.bun/[email protected]/node_modules/zod/index.js
+// node_modules/.bun/[email protected]/node_modules/zod/index.js
var init_zod = __esm(() => {
init_external();
init_external();
@@ -77444,7 +78682,7 @@ var init_env = __esm(() => {
SEND_OPT_OUT_VALUES = ["0", "false", "no", "yes"];
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
import { dirname as dirname17, posix as posix7, sep as sep7 } from "path";
function createModulerModifier() {
const getModuleFromFileName = createGetModuleFromFilename();
@@ -77481,136 +78719,7 @@ function normalizeWindowsPath(path) {
}
var init_module_node = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
-function getFlagDetailFromFlagAndPayload(key, value, payload) {
- return {
- key,
- enabled: typeof value == "string" ? true : value,
- variant: typeof value == "string" ? value : undefined,
- reason: undefined,
- metadata: {
- id: undefined,
- version: undefined,
- payload: payload ? JSON.stringify(payload) : undefined,
- description: undefined
- }
- };
-}
-var normalizeFlagsResponse = (flagsResponse) => {
- if ("flags" in flagsResponse) {
- const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
- const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads
- };
- }
- {
- const featureFlags = flagsResponse.featureFlags ?? {};
- const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
- k,
- parsePayload(v)
- ]));
- const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
- key,
- getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
- ]));
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads,
- flags
- };
- }
-}, getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
- key,
- getFeatureFlagValue(detail)
-]).filter(([, value]) => value !== undefined)), getPayloadsFromFlags = (flags) => {
- const safeFlags = flags ?? {};
- return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
- const details = safeFlags[flag];
- return details.enabled && details.metadata && details.metadata.payload !== undefined;
- }).map((flag) => {
- const payload = safeFlags[flag].metadata?.payload;
- return [
- flag,
- payload ? parsePayload(payload) : undefined
- ];
- }));
-}, getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled, parsePayload = (response) => {
- if (typeof response != "string")
- return response;
- try {
- return JSON.parse(response);
- } catch {
- return response;
- }
-}, MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
- const minimal = {};
- const copyKey = (key) => {
- if (properties[key] !== undefined)
- minimal[key] = properties[key];
- };
- MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
- transportKeys.forEach(copyKey);
- return minimal;
-};
-var init_featureFlagUtils = __esm(() => {
- MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
- "utm_source",
- "utm_medium",
- "utm_campaign",
- "utm_content",
- "utm_term",
- "gad_source",
- "mc_cid",
- "gclid",
- "gclsrc",
- "dclid",
- "gbraid",
- "wbraid",
- "fbclid",
- "msclkid",
- "twclid",
- "li_fat_id",
- "igshid",
- "ttclid",
- "rdt_cid",
- "epik",
- "qclid",
- "sccid",
- "irclid",
- "_kx"
- ];
- MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
- "$feature_flag",
- "$feature_flag_response",
- "$feature_flag_has_experiment",
- "$feature_flag_id",
- "$feature_flag_version",
- "$feature_flag_reason",
- "$feature_flag_request_id",
- "$feature_flag_evaluated_at",
- "$feature_flag_error",
- "locally_evaluated",
- "$groups",
- "$process_person_profile",
- "$geoip_disable",
- "$current_url",
- "$pathname",
- "$referring_domain",
- ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
- "$session_id",
- "$window_id",
- "$lib",
- "$lib_version",
- "$device_id",
- "$is_server"
- ];
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
var types_PostHogPersistedProperty;
var init_types7 = __esm(() => {
types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
@@ -77642,6 +78751,7 @@ var init_types7 = __esm(() => {
PostHogPersistedProperty["PushRegistered"] = "push_registered";
PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
+ PostHogPersistedProperty["SurveysInProgress"] = "surveys_in_progress";
PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
PostHogPersistedProperty["Surveys"] = "surveys";
PostHogPersistedProperty["RemoteConfig"] = "remote_config";
@@ -77651,98 +78761,78 @@ var init_types7 = __esm(() => {
}({});
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
-function isGzipSupported() {
- return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
+function safeJsonStringify(value) {
+ const ancestors = [];
+ return JSON.stringify(value, function(_key, replacementValue) {
+ if (typeof replacementValue == "bigint")
+ return replacementValue.toString();
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
+ return;
+ if (replacementValue instanceof Error)
+ return {
+ name: replacementValue.name,
+ message: replacementValue.message,
+ stack: replacementValue.stack
+ };
+ if (replacementValue && typeof replacementValue == "object") {
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
+ ancestors.pop();
+ if (ancestors.includes(replacementValue))
+ return "[Circular]";
+ ancestors.push(replacementValue);
+ }
+ return replacementValue;
+ }) ?? "null";
}
-async function gzipCompress(input, isDebug = true, options) {
- try {
- const inputBytes = new TextEncoder().encode(input);
- const compressedStream = new globalThis.CompressionStream("gzip");
- const writer = compressedStream.writable.getWriter();
- const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
- try {
- await writer.abort(err);
- } catch {}
- throw err;
- });
- const responsePromise = new Response(compressedStream.readable).blob();
- const [compressed] = await Promise.all([
- responsePromise,
- writePromise
- ]);
- await validateNativeGzip(compressed, inputBytes);
- return compressed;
- } catch (error) {
- if (options?.rethrow)
- throw error;
- if (isDebug)
- console.error("Failed to gzip compress data", error);
- return null;
- }
+var init_string_utils = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
+function isPrimitive(value) {
+ return value === null || typeof value != "object";
}
-var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError", GZIP_MAGIC_FIRST_BYTE = 31, GZIP_MAGIC_SECOND_BYTE = 139, GZIP_DEFLATE_METHOD = 8, hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE, crc32Table, getCrc32Table = () => {
- if (crc32Table)
- return crc32Table;
- crc32Table = [];
- for (let i = 0;i < 256; i++) {
- let crc = i;
- for (let j = 0;j < 8; j++)
- crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
- crc32Table[i] = crc >>> 0;
+function isBuiltin(candidate, className) {
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
+}
+function isError(candidate) {
+ switch (Object.prototype.toString.call(candidate)) {
+ case "[object Error]":
+ case "[object Exception]":
+ case "[object DOMException]":
+ case "[object DOMError]":
+ case "[object WebAssembly.Exception]":
+ return true;
+ default:
+ return isInstanceOf(candidate, Error);
}
- return crc32Table;
-}, crc32 = (bytes) => {
- const table = getCrc32Table();
- let crc = 4294967295;
- for (let i = 0;i < bytes.length; i++)
- crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
- return (4294967295 ^ crc) >>> 0;
-}, throwNativeGzipValidationError = (reason) => {
- const error = new Error(`Native gzip produced invalid output: ${reason}`);
- error.name = NATIVE_GZIP_VALIDATION_ERROR;
- throw error;
-}, validateNativeGzip = async (compressed, inputBytes) => {
- if (compressed.size < 18)
- throwNativeGzipValidationError("too-short");
- const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
- if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
- throwNativeGzipValidationError("invalid-header");
- const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
- if (trailer.getUint32(0, true) !== crc32(inputBytes))
- throwNativeGzipValidationError("invalid-crc");
- const inputSize = inputBytes.length >>> 0;
- if (trailer.getUint32(4, true) !== inputSize)
- throwNativeGzipValidationError("invalid-size");
-};
-var init_gzip = __esm(() => {
- init_types7();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
-function sanitizeString(value) {
- let output = "";
- for (let index = 0;index < value.length; index++) {
- const codeUnit = value.charCodeAt(index);
- if (codeUnit >= 55296 && codeUnit <= 56319) {
- const nextCodeUnit = value.charCodeAt(index + 1);
- if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
- output += value[index] + value[index + 1];
- index++;
- } else
- output += "�";
- } else
- output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
+}
+function isEvent(candidate) {
+ return "u" > typeof Event && isInstanceOf(candidate, Event);
+}
+function isPlainObject6(candidate) {
+ return isBuiltin(candidate, "Object");
+}
+function isInstanceOf(candidate, base) {
+ try {
+ return candidate instanceof base;
+ } catch {
+ return false;
}
- return output;
}
-var MAX_JSON_SAFE_VALUE_DEPTH = 20, MAX_JSON_SAFE_VALUE_ITEMS = 1000, MAX_JSON_SAFE_VALUE_NODES = 1e4, CIRCULAR_VALUE = "[Circular]", TRUNCATED_VALUE = "[Truncated]", UNSERIALIZABLE_VALUE = "[Unserializable]", FUNCTION_VALUE = "[Function]", dateGetTime, dateToISOString;
-var init_json_utils = __esm(() => {
- dateGetTime = Date.prototype.getTime;
- dateToISOString = Date.prototype.toISOString;
+var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject2 = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNull = (x) => x === null, isNullish = (x) => isUndefined(x) || isNull(x), isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
+var init_type_utils = __esm(() => {
+ init_types7();
+ init_string_utils();
+ nativeIsArray = Array.isArray;
+ ObjProto = Object.prototype;
+ type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
+ type_utils_toString = ObjProto.toString;
+ isArray = nativeIsArray || function(obj) {
+ return type_utils_toString.call(obj) === "[object Array]";
+ };
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
var DEFAULT_BLOCKED_UA_STRS, isBlockedUA = function(ua, customBlockedUserAgents = []) {
if (!ua)
return false;
@@ -77780,7 +78870,7 @@ var init_bot_detection = __esm(() => {
"msnbot",
"nessus",
"petalbot",
- "pinterest",
+ "pinterestbot",
"prerender",
"rogerbot",
"screaming frog",
@@ -77834,83 +78924,12 @@ var init_bot_detection = __esm(() => {
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
-function safeJsonStringify(value) {
- const ancestors = [];
- return JSON.stringify(value, function(_key, replacementValue) {
- if (typeof replacementValue == "bigint")
- return replacementValue.toString();
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
- return;
- if (replacementValue instanceof Error)
- return {
- name: replacementValue.name,
- message: replacementValue.message,
- stack: replacementValue.stack
- };
- if (replacementValue && typeof replacementValue == "object") {
- while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
- ancestors.pop();
- if (ancestors.includes(replacementValue))
- return "[Circular]";
- ancestors.push(replacementValue);
- }
- return replacementValue;
- }) ?? "null";
-}
-var init_string_utils = () => {};
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/browser-utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/browser-utils.mjs
var init_browser_utils = __esm(() => {
init_string_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
-function isPrimitive(value) {
- return value === null || typeof value != "object";
-}
-function isBuiltin(candidate, className) {
- return Object.prototype.toString.call(candidate) === `[object ${className}]`;
-}
-function isError(candidate) {
- switch (Object.prototype.toString.call(candidate)) {
- case "[object Error]":
- case "[object Exception]":
- case "[object DOMException]":
- case "[object DOMError]":
- case "[object WebAssembly.Exception]":
- return true;
- default:
- return isInstanceOf(candidate, Error);
- }
-}
-function isEvent(candidate) {
- return typeof Event != "undefined" && isInstanceOf(candidate, Event);
-}
-function isPlainObject6(candidate) {
- return isBuiltin(candidate, "Object");
-}
-function isInstanceOf(candidate, base) {
- try {
- return candidate instanceof base;
- } catch {
- return false;
- }
-}
-var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject2 = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNull = (x) => x === null, isNullish = (x) => isUndefined(x) || isNull(x), isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
-var init_type_utils = __esm(() => {
- init_types7();
- init_string_utils();
- nativeIsArray = Array.isArray;
- ObjProto = Object.prototype;
- type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
- type_utils_toString = ObjProto.toString;
- isArray = nativeIsArray || function(obj) {
- return type_utils_toString.call(obj) === "[object Array]";
- };
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
function clampToRange(value, min, max, logger, fallbackValue) {
if (min > max) {
logger.warn("min cannot be greater than max.");
@@ -77927,13 +78946,13 @@ function clampToRange(value, min, max, logger, fallbackValue) {
return min;
}
logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
- return clampToRange(fallbackValue || max, min, max, logger);
+ return clampToRange(fallbackValue ?? max, min, max, logger);
}
var init_number_utils = __esm(() => {
init_type_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
function resolveExceptionRateLimiterConfig(config = {}) {
return {
refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,
@@ -77987,7 +79006,7 @@ var init_bucketed_rate_limiter = __esm(() => {
init_number_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
class UUID {
constructor(bytes) {
this.bytes = bytes;
@@ -78156,13 +79175,13 @@ class V7Generator {
}
}
var DIGITS = "0123456789abcdef", getDefaultRandom = () => ({
- nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random()) >>> 0
}), defaultGenerator, uuidv7 = () => uuidv7obj().toString(), uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
var init_uuidv7 = __esm(() => {
- /*! For license information please see uuidv7.mjs.LICENSE.txt */
+ /*! LICENSE: uuidv7.mjs.LICENSE.txt */
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
class PromiseQueue {
add(promise) {
const promiseUUID = uuidv7();
@@ -78204,7 +79223,7 @@ var init_promise_queue = __esm(() => {
init_uuidv7();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
function createConsole(consoleLike = console) {
const lockedMethods = {
log: consoleLike.log.bind(consoleLike),
@@ -78246,8 +79265,8 @@ var _createLogger = (prefix, maybeCall, consoleLike) => {
}, passThrough = (fn) => fn();
var init_logger4 = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
-var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", GOOGLE_SEARCH_APP = "Google Search App", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
+var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", CLAUDE = "Claude", CODEX = "Codex", CHATGPT = "ChatGPT", GOOGLE_SEARCH_APP = "Google Search App", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, AI_APP_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
var init_user_agent_utils = __esm(() => {
init_string_utils();
init_type_utils();
@@ -78267,6 +79286,7 @@ var init_user_agent_utils = __esm(() => {
GENERIC_MOBILE = GENERIC + " " + MOBILE.toLowerCase();
GENERIC_TABLET = GENERIC + " " + TABLET.toLowerCase();
DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
+ AI_APP_VERSION_REGEX = new RegExp("(" + CLAUDE + "|" + CODEX + "|" + CHATGPT + ")\\/" + BROWSER_VERSION_REGEX_SUFFIX);
XBOX_REGEX = new RegExp(XBOX, "i");
PLAYSTATION_REGEX = new RegExp(PLAYSTATION + " \\w+", "i");
NINTENDO_REGEX = new RegExp(NINTENDO + " \\w+", "i");
@@ -78343,6 +79363,15 @@ var init_user_agent_utils = __esm(() => {
[BRAVE]: [
new RegExp(BRAVE + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
+ [CLAUDE]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CODEX]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CHATGPT]: [
+ AI_APP_VERSION_REGEX
+ ],
[DUCKDUCKGO]: [
new RegExp("(DuckDuckGo|Ddg)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
@@ -78515,13 +79544,139 @@ var init_user_agent_utils = __esm(() => {
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/webview-app-utils.mjs
+var init_webview_app_utils = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
+function sanitizeString(value) {
+ let output = "";
+ for (let index = 0;index < value.length; index++) {
+ const codeUnit = value.charCodeAt(index);
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
+ const nextCodeUnit = value.charCodeAt(index + 1);
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
+ output += value[index] + value[index + 1];
+ index++;
+ } else
+ output += "�";
+ } else
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
+ }
+ return output;
+}
+function assignUserAttributes(target, source) {
+ if (!source)
+ return target;
+ let keys = [];
+ try {
+ keys = Object.keys(source);
+ } catch {
+ keys = [];
+ }
+ for (const key of keys) {
+ let value;
+ try {
+ value = source[key];
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ return target;
+}
+var MAX_JSON_SAFE_VALUE_DEPTH = 20, MAX_JSON_SAFE_VALUE_ITEMS = 1000, MAX_JSON_SAFE_VALUE_NODES = 1e4, CIRCULAR_VALUE = "[Circular]", TRUNCATED_VALUE = "[Truncated]", UNSERIALIZABLE_VALUE = "[Unserializable]", FUNCTION_VALUE = "[Function]", dateGetTime, dateToISOString;
+var init_json_utils = __esm(() => {
+ dateGetTime = Date.prototype.getTime;
+ dateToISOString = Date.prototype.toISOString;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/retry-after.mjs
+function parseRetryAfterMs(value, now = Date.now()) {
+ if (typeof value != "string" || !value)
+ return;
+ const raw = value.trim();
+ const trimmed = /^\d+\s*,/.test(raw) ? raw.slice(0, raw.indexOf(",")).trim() : raw;
+ if (/^\d+$/.test(trimmed)) {
+ const ms = 1000 * Math.min(Number(trimmed), MAX_RETRY_AFTER_MS / 1000);
+ return ms > 0 ? ms : undefined;
+ }
+ if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(trimmed))
+ return;
+ const date = /^\w{3} \w{3} /.test(trimmed) ? trimmed + " GMT" : trimmed;
+ const ms = Date.parse(date) - now;
+ if (!Number.isFinite(ms) || ms <= 0)
+ return;
+ return Math.min(ms, MAX_RETRY_AFTER_MS);
+}
+
+class RetryAfterWindow {
+ record(outcome) {
+ if (outcome.kind === "too-large")
+ return;
+ if (outcome.kind !== "retry-later")
+ return void this.reset();
+ if (!outcome.retryAfterMs)
+ return;
+ const open = this.isOpen();
+ const now = Date.now();
+ const asked = Math.min(outcome.retryAfterMs, MAX_RETRY_AFTER_MS);
+ if (!open) {
+ this._installedAt = now;
+ this._until = now + asked;
+ return;
+ }
+ this._until = Math.max(this._until, Math.min(now + asked, this._installedAt + MAX_RETRY_AFTER_MS));
+ }
+ remainingMs() {
+ const now = Date.now();
+ if (now < this._installedAt - CLOCK_STEP_TOLERANCE_MS) {
+ this.reset();
+ return 0;
+ }
+ const remaining = Math.min(MAX_RETRY_AFTER_MS, Math.max(0, this._until - now));
+ if (remaining === 0)
+ this.reset();
+ return remaining;
+ }
+ isOpen() {
+ return this.remainingMs() > 0;
+ }
+ reset() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+ constructor() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+}
+var MAX_RETRY_AFTER_MS = 300000, CLOCK_STEP_TOLERANCE_MS = 5000;
+var init_retry_after = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
function isValidUUID(value) {
return typeof value == "string" && UUID_REGEX.test(value);
}
function getEventUuid(uuid, generateUuid) {
return isValidUUID(uuid) ? uuid : generateUuid();
}
+function createNamedError(name, message) {
+ const error = new Error(message);
+ try {
+ Object.defineProperty(error, "name", {
+ value: name,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ } catch {}
+ return error;
+}
function removeTrailingSlash(url) {
return url?.replace(/\/+$/, "");
}
@@ -78578,9 +79733,11 @@ function allSettled(promises) {
reason
}))));
}
-var STRING_FORMAT = "utf8", UUID_REGEX;
+var STRING_FORMAT = "utf8", UUID_REGEX, isPromise = (obj) => obj && typeof obj.then == "function";
var init_utils = __esm(() => {
+ init_type_utils();
init_json_utils();
+ init_retry_after();
init_bot_detection();
init_browser_utils();
init_bucketed_rate_limiter();
@@ -78590,902 +79747,380 @@ var init_utils = __esm(() => {
init_promise_queue();
init_logger4();
init_user_agent_utils();
+ init_webview_app_utils();
UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
-function newState() {
- return {
- ancestors: new WeakSet,
- remainingNodes: MAX_JSON_SAFE_VALUE_NODES
- };
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
+function getFilenameToChunkIdMap(stackParser) {
+ const chunkIdMap = globalThis._posthogChunkIds;
+ if (!chunkIdMap)
+ return;
+ const chunkIdKeys = Object.keys(chunkIdMap);
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
+ return cachedFilenameChunkIds;
+ lastKeysCount = chunkIdKeys.length;
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
+ if (!parsedStackResults)
+ parsedStackResults = {};
+ const result = parsedStackResults[stackKey];
+ if (result)
+ acc[result[0]] = result[1];
+ else {
+ const parsedStack = stackParser(stackKey);
+ for (let i = parsedStack.length - 1;i >= 0; i--) {
+ const stackFrame = parsedStack[i];
+ const filename = stackFrame?.filename;
+ const chunkId = chunkIdMap[stackKey];
+ if (filename && chunkId) {
+ acc[filename] = chunkId;
+ parsedStackResults[stackKey] = [
+ filename,
+ chunkId
+ ];
+ break;
+ }
+ }
+ }
+ return acc;
+ }, {});
+ return cachedFilenameChunkIds;
}
-function toOtlpKeyValueList(attrs, logger) {
- try {
- return encodeKeyValueList(attrs, logger, newState(), 0);
- } catch {
- return [];
+var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
+var init_chunk_ids = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
+class ErrorPropertiesBuilder {
+ constructor(coercers, stackParser, modifiers = []) {
+ this.coercers = coercers;
+ this.stackParser = stackParser;
+ this.modifiers = modifiers;
}
-}
-function encodeAnyValue(value, logger, state, depth) {
- if (state.remainingNodes <= 0)
- return {
- stringValue: TRUNCATED_VALUE
- };
- state.remainingNodes--;
- if (isBoolean(value))
- return {
- boolValue: value
+ buildFromUnknown(input, hint = {}) {
+ const providedMechanism = hint && hint.mechanism;
+ const mechanism = providedMechanism || {
+ handled: true,
+ type: "generic"
};
- if (typeof value == "number") {
- if (!Number.isFinite(value))
- return {
- stringValue: String(value)
- };
- if (Number.isInteger(value)) {
- if (Number.isSafeInteger(value))
- return {
- intValue: String(value)
- };
- if (typeof BigInt == "undefined")
- return {
- stringValue: String(value)
- };
- const decimal = BigInt(value).toString();
- if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
- logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
- return {
- stringValue: decimal
- };
- }
- return {
- intValue: decimal
- };
- }
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
+ const exceptionWithCause = coercingContext.apply(input);
+ const parsingContext = this.buildParsingContext(hint);
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
return {
- doubleValue: value
+ $exception_list: exceptionList,
+ $exception_level: "error"
};
}
- if (typeof value == "string")
- return {
- stringValue: sanitizeString(value)
- };
- if (typeof value == "function")
+ async modifyFrames(exceptionList) {
+ for (const exc of exceptionList)
+ if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
+ exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
+ return exceptionList;
+ }
+ coerceFallback(ctx) {
return {
- stringValue: FUNCTION_VALUE
+ type: "Error",
+ value: "Unknown error",
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
};
- if (typeof value == "symbol")
+ }
+ parseStacktrace(err, ctx) {
+ let cause;
+ if (err.cause != null)
+ cause = this.parseStacktrace(err.cause, ctx);
+ let stack;
+ if (err.stack != "" && err.stack != null)
+ try {
+ stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
+ } catch {}
return {
- stringValue: String(value)
+ ...err,
+ cause,
+ stack,
+ errors: err.errors?.map((child) => this.parseStacktrace(child, ctx))
};
- if (typeof value == "object" && value !== null) {
- if (state.ancestors.has(value))
- return {
- stringValue: CIRCULAR_VALUE
- };
- if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
- return {
- stringValue: TRUNCATED_VALUE
+ }
+ applyChunkIds(frames, chunkIdMap) {
+ return frames.map((frame) => {
+ if (frame.filename && chunkIdMap)
+ frame.chunk_id = chunkIdMap[frame.filename];
+ return frame;
+ });
+ }
+ applyCoercers(input, ctx) {
+ for (const adapter of this.coercers)
+ if (adapter.match(input))
+ return adapter.coerce(input, ctx);
+ return this.coerceFallback(ctx);
+ }
+ async applyModifiers(frames) {
+ let newFrames = frames;
+ for (const modifier of this.modifiers)
+ newFrames = await modifier(newFrames);
+ return newFrames;
+ }
+ convertToExceptionList(exceptionWithStack, mechanism) {
+ const exceptionList = [];
+ const append = (exception, parentId, source) => {
+ const exceptionId = exceptionList.length;
+ const entryMechanism = parentId === undefined ? {
+ type: typeof mechanism.type == "string" && mechanism.type.length > 0 ? mechanism.type : "generic",
+ ...typeof mechanism.handled == "boolean" ? {
+ handled: mechanism.handled
+ } : mechanism.handled === undefined ? {
+ handled: true
+ } : {},
+ synthetic: typeof mechanism.synthetic == "boolean" ? mechanism.synthetic : exception.synthetic,
+ exception_id: exceptionId
+ } : {
+ type: "chained",
+ source,
+ synthetic: exception.synthetic,
+ exception_id: exceptionId,
+ parent_id: parentId
};
- if (value instanceof Date) {
- const time = value.getTime();
- const iso = Number.isFinite(time) ? value.toISOString() : String(value);
- return {
- stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ const currentException = {
+ type: exception.type,
+ value: exception.value,
+ mechanism: entryMechanism
};
- }
- state.ancestors.add(value);
+ if (exception.stack)
+ currentException.stacktrace = {
+ type: "raw",
+ frames: exception.stack
+ };
+ exceptionList.push(currentException);
+ if (exception.cause)
+ append(exception.cause, exceptionId, "cause");
+ for (const child of exception.errors ?? [])
+ append(child, exceptionId, "member");
+ };
+ append(exceptionWithStack);
+ return exceptionList;
+ }
+ buildParsingContext(hint) {
+ const context = {
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
+ skipFirstLines: hint.skipFirstLines ?? 1
+ };
+ return context;
+ }
+ getAggregateErrors(input) {
try {
- try {
- const toJSON = value.toJSON;
- if (typeof toJSON == "function")
- return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
- } catch {}
- if (isArray(value))
- return {
- arrayValue: {
- values: encodeArrayValues(value, logger, state, depth + 1)
+ if (isError(input)) {
+ let prototype = Object.getPrototypeOf(input);
+ for (let depth = 0;prototype && depth < MAX_ERROR_PROTOTYPE_DEPTH; depth++) {
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
+ if (typeof constructor == "function" && constructor.name === "AggregateError") {
+ const errors = input.errors;
+ return isArray(errors) ? errors : undefined;
}
- };
- return {
- kvlistValue: {
- values: encodeKeyValueList(value, logger, state, depth + 1)
+ prototype = Object.getPrototypeOf(prototype);
}
- };
- } finally {
- state.ancestors.delete(value);
- }
+ }
+ } catch {}
}
- return {
- stringValue: sanitizeString(String(value))
- };
-}
-function encodeArrayValues(values, logger, state, depth) {
- const result = [];
- const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
- let index = 0;
- for (;index < itemCount && state.remainingNodes > 0; index++)
- try {
- const element = index in values ? values[index] : undefined;
- if (isNullish(element))
- continue;
- result.push(encodeAnyValue(element, logger, state, depth));
- } catch {
- result.push({
- stringValue: UNSERIALIZABLE_VALUE
- });
- }
- if (values.length > index)
- result.push({
- stringValue: TRUNCATED_VALUE
- });
- return result;
-}
-function encodeKeyValueList(attrs, logger, state, depth) {
- const result = [];
- for (const key in attrs)
- if (propertyIsEnumerable.call(attrs, key)) {
- if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
- logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
- break;
+ buildCoercingContext(mechanism, hint, depth = 0) {
+ let count = 0;
+ let memberInspections = 0;
+ let hasAggregate = false;
+ const seen = new Set;
+ const wrappers = [];
+ const skipped = {};
+ const coerce = (input, depth, wrapperDepth = 0) => {
+ const ctx = createContext(depth, wrapperDepth);
+ const forward = ctx.apply;
+ ctx.apply = (nextInput) => {
+ wrappers.push(input);
+ try {
+ return forward(nextInput);
+ } finally {
+ wrappers.pop();
+ }
+ };
+ if (wrapperDepth > MAX_WRAPPER_RECURSION || wrapperDepth > 0 && wrappers.indexOf(input) !== -1)
+ return this.coerceFallback(ctx);
+ const isReference = typeof input == "object" && input !== null || typeof input == "function";
+ if (wrapperDepth === 0 && count >= MAX_EXCEPTIONS || isReference && seen.has(input))
+ return;
+ if (isReference)
+ seen.add(input);
+ if (wrapperDepth === 0)
+ count++;
+ const errors = this.getAggregateErrors(input);
+ hasAggregate ||= !!errors;
+ let exception;
+ try {
+ exception = this.applyCoercers(input, ctx);
+ if (!exception)
+ throw skipped;
+ } catch (error) {
+ if (error === skipped) {
+ if (wrapperDepth === 0)
+ count--;
+ return;
+ }
+ if (!hasAggregate)
+ throw error;
+ exception = this.coerceFallback(ctx);
}
+ if (!errors || count >= MAX_EXCEPTIONS)
+ return exception;
+ let length;
try {
- const value = attrs[key];
- if (isNull(value) || isUndefined(value))
- continue;
- result.push({
- key: sanitizeString(key),
- value: encodeAnyValue(value, logger, state, depth)
- });
+ length = errors.length;
} catch {
- result.push({
- key: sanitizeString(key),
- value: {
- stringValue: UNSERIALIZABLE_VALUE
- }
- });
+ return exception;
+ }
+ if (!Number.isInteger(length) || length < 0 || length > 4294967295)
+ return exception;
+ const children = [];
+ for (let index = 0;count < MAX_EXCEPTIONS && memberInspections < MAX_AGGREGATE_MEMBER_INSPECTIONS && index < length; index++) {
+ memberInspections++;
+ let child;
+ try {
+ child = ctx.next(errors[index]);
+ } catch {
+ count++;
+ child = this.coerceFallback(createContext(depth + 1));
+ }
+ if (child)
+ children.push(child);
}
- }
- return result;
+ return {
+ ...exception,
+ errors: children
+ };
+ };
+ const createContext = (depth, wrapperDepth = 0) => ({
+ ...hint,
+ syntheticException: depth == 0 ? hint.syntheticException : undefined,
+ mechanism: depth == 0 ? mechanism : {},
+ apply: (input) => {
+ const exception = coerce(input, depth, wrapperDepth + 1);
+ if (!exception)
+ throw skipped;
+ return exception;
+ },
+ next: (input) => coerce(input, depth + 1)
+ });
+ const context = createContext(depth);
+ return {
+ ...context,
+ apply: (input) => coerce(input, depth) ?? this.coerceFallback(context)
+ };
+ }
}
-var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY, INT64_RANGE_LIMIT = 9223372036854776000, propertyIsEnumerable;
-var init_logs_utils = __esm(() => {
- init_utils();
- init_json_utils();
- OTLP_SEVERITY_MAP = {
- trace: {
- text: "TRACE",
- number: 1
- },
- debug: {
- text: "DEBUG",
- number: 5
- },
- info: {
- text: "INFO",
- number: 9
- },
- warn: {
- text: "WARN",
- number: 13
- },
- error: {
- text: "ERROR",
- number: 17
- },
- fatal: {
- text: "FATAL",
- number: 21
- }
- };
- DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
- propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/index.mjs
-var init_logs = __esm(() => {
- init_logs_utils();
- init_types7();
+var MAX_EXCEPTIONS = 50, MAX_AGGREGATE_MEMBER_INSPECTIONS = 1000, MAX_ERROR_PROTOTYPE_DEPTH = 100, MAX_WRAPPER_RECURSION = 4;
+var init_error_properties_builder = __esm(() => {
init_utils();
+ init_chunk_ids();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
-function msToUnixNano(ms) {
- return String(ms) + "000000";
-}
-function seriesKey(type, name, unit, attributes) {
- let attrsKey = "";
- if (attributes) {
- const keys = Object.keys(attributes).sort();
- attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
- }
- return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
-}
-function bucketIndexFor(value, bounds) {
- for (let i = 0;i < bounds.length; i++)
- if (value <= bounds[i])
- return i;
- return bounds.length;
-}
-function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
- return {
- ...config.resourceAttributes,
- "service.name": config.serviceName || "unknown_service",
- ...config.environment && {
- "deployment.environment": config.environment
- },
- ...config.serviceVersion && {
- "service.version": config.serviceVersion
- },
- "telemetry.sdk.name": scopeName,
- "telemetry.sdk.version": scopeVersion
- };
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
+function isAppFilename(filename) {
+ if (!filename || filename === ANONYMOUS_FILENAME)
+ return false;
+ const scheme = URL_SCHEME.exec(filename);
+ return !scheme || APP_URL_SCHEMES.includes(scheme[1].toLowerCase());
}
-function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
- return {
- resourceMetrics: [
- {
- resource: {
- attributes: toOtlpKeyValueList(resourceAttributes)
- },
- scopeMetrics: [
- {
- scope: {
- name: scopeName,
- version: scopeVersion
- },
- metrics
- }
- ]
- }
- ]
+function createFrame(platform, filename, func, lineno, colno) {
+ const frame = {
+ platform,
+ filename,
+ function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
+ in_app: isAppFilename(filename)
};
+ if (!isUndefined(lineno))
+ frame.lineno = lineno;
+ if (!isUndefined(colno))
+ frame.colno = colno;
+ return frame;
}
-var DEFAULT_HISTOGRAM_BOUNDS;
-var init_metrics_utils = __esm(() => {
- init_logs_utils();
- DEFAULT_HISTOGRAM_BOUNDS = [
- 0,
- 5,
- 10,
- 25,
- 50,
- 75,
- 100,
- 250,
- 500,
- 750,
- 1000,
- 2500,
- 5000,
- 7500,
- 1e4
+var UNKNOWN_FUNCTION = "?", ANONYMOUS_FILENAME = "<anonymous>", URL_SCHEME, APP_URL_SCHEMES;
+var init_base = __esm(() => {
+ init_utils();
+ URL_SCHEME = /^([a-z][a-z0-9.+-]+):/i;
+ APP_URL_SCHEMES = [
+ "http",
+ "https",
+ "file",
+ "blob",
+ "app",
+ "capacitor",
+ "ionic",
+ "webpack",
+ "webpack-internal",
+ "ng"
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
-function resolveMetricsConfig(config) {
- const resourceAttributes = config?.resourceAttributes;
- return {
- serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
- serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
- environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
- resourceAttributes,
- beforeSend: config?.beforeSend,
- flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
- maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
- };
-}
-var DEFAULT_FLUSH_INTERVAL_MS = 1e4, DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
-var init_config2 = () => {};
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
+var extractSafariExtensionDetails = (func, filename) => {
+ const isSafariExtension = func.indexOf("safari-extension") !== -1;
+ const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
+ return isSafariExtension || isSafariWebExtension ? [
+ func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
+ ] : [
+ func,
+ filename
+ ];
+};
+var init_safari = __esm(() => {
+ init_base();
+});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
-class PostHogMetrics {
- constructor(_instance, _config, _logger) {
- this._instance = _instance;
- this._config = _config;
- this._logger = _logger;
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- this._generation = 0;
- }
- count(name, value = 1, options) {
- this._capture({
- name,
- type: "count",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- gauge(name, value, options) {
- this._capture({
- name,
- type: "gauge",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
+var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser = (line, platform) => {
+ const noFnParts = chromeRegexNoFnName.exec(line);
+ if (noFnParts) {
+ const [, filename, line, col] = noFnParts;
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
}
- histogram(name, value, options) {
- this._capture({
- name,
- type: "histogram",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
+ const parts = chromeRegex.exec(line);
+ if (parts) {
+ const isEval = parts[2] && parts[2].indexOf("eval") === 0;
+ if (isEval) {
+ const subMatch = chromeEvalRegex.exec(parts[2]);
+ if (subMatch) {
+ parts[2] = subMatch[1];
+ parts[3] = subMatch[2];
+ parts[4] = subMatch[3];
+ }
+ }
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
}
- flush() {
- const prev = this._flushPromise;
- const run = async () => {
- if (prev)
- await prev.catch(() => {});
- await this._doFlush();
- };
- const p = run().finally(() => {
- if (this._flushPromise === p)
- this._flushPromise = null;
- });
- this._flushPromise = p;
- return p;
- }
- drainWindow() {
- if (this._series.size === 0)
- return null;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- return this._buildPayload(window);
- }
- reset() {
- this._generation++;
- this._clearFlushTimer();
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- }
- _capture(sample) {
- if (this._instance.isDisabled || this._instance.optedOut)
- return;
- const filtered = this._runBeforeSend(sample);
- if (filtered === null)
- return;
- if (!filtered.name || typeof filtered.name != "string")
- return void this._logger.warn("Dropping metric with empty name");
- if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
- return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
- if (filtered.type === "count" && filtered.value < 0)
- return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
- let attributes;
- let key;
- try {
- attributes = filtered.attributes ? {
- ...filtered.attributes
- } : undefined;
- key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
- } catch (e) {
- this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
- return;
- }
- let state = this._series.get(key);
- if (!state) {
- if (!this._admitNewSeries())
- return;
- state = {
- name: filtered.name,
- type: filtered.type,
- unit: filtered.unit,
- attributes,
- windowStartMs: Date.now()
- };
- this._series.set(key, state);
- }
- const seenType = this._typeByName.get(filtered.name);
- if (seenType === undefined)
- this._typeByName.set(filtered.name, filtered.type);
- else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
- this._typeCollisionWarned.add(filtered.name);
- this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
- }
- this._fold(state, filtered.value);
- this._armFlushTimer();
- }
- _admitNewSeries() {
- if (this._series.size < this._config.maxSeriesPerFlush)
- return true;
- if (!this._seriesCapWarned) {
- this._seriesCapWarned = true;
- this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
- }
- return false;
- }
- _fold(state, value) {
- switch (state.type) {
- case "count":
- state.total = (state.total ?? 0) + value;
- break;
- case "gauge":
- state.last = value;
- break;
- case "histogram": {
- if (!state.hist)
- state.hist = {
- count: 0,
- sum: 0,
- min: value,
- max: value,
- bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
- };
- const hist = state.hist;
- hist.count += 1;
- hist.sum += value;
- hist.min = Math.min(hist.min, value);
- hist.max = Math.max(hist.max, value);
- hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
- break;
- }
- }
- }
- _runBeforeSend(sample) {
- const beforeSend = this._config.beforeSend;
- if (!beforeSend)
- return sample;
- const fns = isArray(beforeSend) ? beforeSend : [
- beforeSend
- ];
- let result = sample;
- for (const fn of fns)
- try {
- const next = fn(result);
- if (!next) {
- this._logger.info("Metric was rejected in beforeSend function");
- return null;
- }
- result = next;
- } catch (e) {
- this._logger.error("Error in beforeSend function for metric:", e);
- return null;
- }
- return result;
- }
- _armFlushTimer() {
- if (this._flushTimer)
- return;
- this._flushTimer = safeSetTimeout(() => {
- this._flushTimer = undefined;
- this.flush().catch((e) => {
- this._logger.error("Metrics flush failed:", e);
- });
- }, this._config.flushIntervalMs);
- }
- _clearFlushTimer() {
- if (this._flushTimer) {
- clearTimeout(this._flushTimer);
- this._flushTimer = undefined;
- }
- }
- async _doFlush() {
- if (this._series.size === 0)
- return;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- const generation = this._generation;
- const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
- if (generation !== this._generation)
- return;
- switch (outcome.kind) {
- case "ok":
- return;
- case "retry-later":
- this._mergeWindowBack(window);
- this._armFlushTimer();
- return;
- case "too-large":
- this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
- return;
- case "fatal":
- this._logger.error("Failed to send metrics batch:", outcome.error);
- return;
- }
- }
- _buildPayload(window) {
- return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
- }
- _buildMetrics(window) {
- const nowNano = msToUnixNano(Date.now());
- const byMetric = new Map;
- for (const state of window.values()) {
- const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
- let metric = byMetric.get(metricKey);
- if (!metric) {
- metric = {
- name: state.name,
- ...state.unit && {
- unit: state.unit
- }
- };
- if (state.type === "count")
- metric.sum = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- isMonotonic: true,
- dataPoints: []
- };
- else if (state.type === "gauge")
- metric.gauge = {
- dataPoints: []
- };
- else
- metric.histogram = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- dataPoints: []
- };
- byMetric.set(metricKey, metric);
- }
- const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
- const startNano = msToUnixNano(state.windowStartMs);
- if (state.type === "count") {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- asDouble: state.total ?? 0
- };
- metric.sum.dataPoints.push(dp);
- } else if (state.type === "gauge") {
- const dp = {
- attributes,
- timeUnixNano: nowNano,
- asDouble: state.last ?? 0
- };
- metric.gauge.dataPoints.push(dp);
- } else if (state.hist) {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- count: state.hist.count,
- sum: state.hist.sum,
- min: state.hist.min,
- max: state.hist.max,
- bucketCounts: state.hist.bucketCounts,
- explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
- };
- metric.histogram.dataPoints.push(dp);
- }
- }
- return Array.from(byMetric.values());
- }
- _mergeWindowBack(window) {
- for (const [key, old] of window) {
- const current = this._series.get(key);
- if (!current) {
- if (this._admitNewSeries())
- this._series.set(key, old);
- continue;
- }
- current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
- switch (current.type) {
- case "count":
- current.total = (current.total ?? 0) + (old.total ?? 0);
- break;
- case "gauge":
- break;
- case "histogram":
- if (old.hist)
- if (current.hist) {
- current.hist.count += old.hist.count;
- current.hist.sum += old.hist.sum;
- current.hist.min = Math.min(current.hist.min, old.hist.min);
- current.hist.max = Math.max(current.hist.max, old.hist.max);
- for (let i = 0;i < current.hist.bucketCounts.length; i++)
- current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
- } else
- current.hist = old.hist;
- break;
- }
- }
- }
-}
-var OTLP_TEMPORALITY_DELTA = 1;
-var init_metrics = __esm(() => {
- init_utils();
- init_logs_utils();
- init_metrics_utils();
- init_config2();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/surveys/validation.mjs
-var init_validation = __esm(() => {
- init_types7();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/cookie.mjs
-var init_cookie = __esm(() => {
- init_utils();
- init_uuidv7();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
-class SimpleEventEmitter {
- constructor() {
- this.events = {};
- this.events = {};
- }
- on(event, listener) {
- if (!this.events[event])
- this.events[event] = [];
- this.events[event].push(listener);
- return () => {
- this.events[event] = this.events[event].filter((x) => x !== listener);
- };
- }
- emit(event, payload) {
- for (const listener of this.events[event] || [])
- listener(payload);
- for (const listener of this.events["*"] || [])
- listener(event, payload);
- }
-}
-var init_eventemitter = () => {};
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
-function getFilenameToChunkIdMap(stackParser) {
- const chunkIdMap = globalThis._posthogChunkIds;
- if (!chunkIdMap)
- return;
- const chunkIdKeys = Object.keys(chunkIdMap);
- if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
- return cachedFilenameChunkIds;
- lastKeysCount = chunkIdKeys.length;
- cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
- if (!parsedStackResults)
- parsedStackResults = {};
- const result = parsedStackResults[stackKey];
- if (result)
- acc[result[0]] = result[1];
- else {
- const parsedStack = stackParser(stackKey);
- for (let i = parsedStack.length - 1;i >= 0; i--) {
- const stackFrame = parsedStack[i];
- const filename = stackFrame?.filename;
- const chunkId = chunkIdMap[stackKey];
- if (filename && chunkId) {
- acc[filename] = chunkId;
- parsedStackResults[stackKey] = [
- filename,
- chunkId
- ];
- break;
- }
- }
- }
- return acc;
- }, {});
- return cachedFilenameChunkIds;
-}
-var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
-var init_chunk_ids = () => {};
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
-class ErrorPropertiesBuilder {
- constructor(coercers, stackParser, modifiers = []) {
- this.coercers = coercers;
- this.stackParser = stackParser;
- this.modifiers = modifiers;
- }
- buildFromUnknown(input, hint = {}) {
- const providedMechanism = hint && hint.mechanism;
- const mechanism = providedMechanism || {
- handled: true,
- type: "generic"
- };
- const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
- const exceptionWithCause = coercingContext.apply(input);
- const parsingContext = this.buildParsingContext(hint);
- const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
- const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
- return {
- $exception_list: exceptionList,
- $exception_level: "error"
- };
- }
- async modifyFrames(exceptionList) {
- for (const exc of exceptionList)
- if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
- exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
- return exceptionList;
- }
- coerceFallback(ctx) {
- return {
- type: "Error",
- value: "Unknown error",
- stack: ctx.syntheticException?.stack,
- synthetic: true
- };
- }
- parseStacktrace(err, ctx) {
- let cause;
- if (err.cause != null)
- cause = this.parseStacktrace(err.cause, ctx);
- let stack;
- if (err.stack != "" && err.stack != null)
- stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
- return {
- ...err,
- cause,
- stack
- };
- }
- applyChunkIds(frames, chunkIdMap) {
- return frames.map((frame) => {
- if (frame.filename && chunkIdMap)
- frame.chunk_id = chunkIdMap[frame.filename];
- return frame;
- });
- }
- applyCoercers(input, ctx) {
- for (const adapter of this.coercers)
- if (adapter.match(input))
- return adapter.coerce(input, ctx);
- return this.coerceFallback(ctx);
- }
- async applyModifiers(frames) {
- let newFrames = frames;
- for (const modifier of this.modifiers)
- newFrames = await modifier(newFrames);
- return newFrames;
- }
- convertToExceptionList(exceptionWithStack, mechanism) {
- const currentException = {
- type: exceptionWithStack.type,
- value: exceptionWithStack.value,
- mechanism: {
- type: mechanism.type ?? "generic",
- handled: mechanism.handled ?? true,
- synthetic: exceptionWithStack.synthetic ?? false
- }
- };
- if (exceptionWithStack.stack)
- currentException.stacktrace = {
- type: "raw",
- frames: exceptionWithStack.stack
- };
- const exceptionList = [
- currentException
- ];
- if (exceptionWithStack.cause != null)
- exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
- ...mechanism,
- handled: true
- }));
- return exceptionList;
- }
- buildParsingContext(hint) {
- const context = {
- chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
- skipFirstLines: hint.skipFirstLines ?? 1
- };
- return context;
- }
- buildCoercingContext(mechanism, hint, depth = 0) {
- const coerce = (input, depth) => {
- if (!(depth <= MAX_CAUSE_RECURSION))
- return;
- {
- const ctx = this.buildCoercingContext(mechanism, hint, depth);
- return this.applyCoercers(input, ctx);
- }
- };
- const context = {
- ...hint,
- syntheticException: depth == 0 ? hint.syntheticException : undefined,
- mechanism,
- apply: (input) => coerce(input, depth),
- next: (input) => coerce(input, depth + 1)
- };
- return context;
- }
-}
-var MAX_CAUSE_RECURSION = 4;
-var init_error_properties_builder = __esm(() => {
- init_utils();
- init_chunk_ids();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
-function createFrame(platform, filename, func, lineno, colno) {
- const frame = {
- platform,
- filename,
- function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
- in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
- };
- if (!isUndefined(lineno))
- frame.lineno = lineno;
- if (!isUndefined(colno))
- frame.colno = colno;
- return frame;
-}
-var UNKNOWN_FUNCTION = "?", MASKED_URL_PREFIX = "webkit-masked-url://", ANONYMOUS_FILENAME = "<anonymous>";
-var init_base = __esm(() => {
- init_utils();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
-var extractSafariExtensionDetails = (func, filename) => {
- const isSafariExtension = func.indexOf("safari-extension") !== -1;
- const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
- return isSafariExtension || isSafariWebExtension ? [
- func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
- isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
- ] : [
- func,
- filename
- ];
-};
-var init_safari = __esm(() => {
- init_base();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
-var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser = (line, platform) => {
- const noFnParts = chromeRegexNoFnName.exec(line);
- if (noFnParts) {
- const [, filename, line, col] = noFnParts;
- return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
- }
- const parts = chromeRegex.exec(line);
- if (parts) {
- const isEval = parts[2] && parts[2].indexOf("eval") === 0;
- if (isEval) {
- const subMatch = chromeEvalRegex.exec(parts[2]);
- if (subMatch) {
- parts[2] = subMatch[1];
- parts[3] = subMatch[2];
- parts[4] = subMatch[3];
- }
- }
- const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
- return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
- }
-};
-var init_chrome = __esm(() => {
- init_base();
- init_safari();
- chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
- chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
- chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
-var geckoREgex, geckoEvalRegex, geckoStackLineParser = (line, platform) => {
- const parts = geckoREgex.exec(line);
- if (parts) {
- const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
- if (isEval) {
- const subMatch = geckoEvalRegex.exec(parts[3]);
- if (subMatch) {
- parts[1] = parts[1] || "eval";
- parts[3] = subMatch[1];
- parts[4] = subMatch[2];
- parts[5] = "";
- }
- }
- let filename = parts[3];
- let func = parts[1] || UNKNOWN_FUNCTION;
- [func, filename] = extractSafariExtensionDetails(func, filename);
- return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
+};
+var init_chrome = __esm(() => {
+ init_base();
+ init_safari();
+ chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
+ chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
+ chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
+var geckoREgex, geckoEvalRegex, geckoStackLineParser = (line, platform) => {
+ const parts = geckoREgex.exec(line);
+ if (parts) {
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
+ if (isEval) {
+ const subMatch = geckoEvalRegex.exec(parts[3]);
+ if (subMatch) {
+ parts[1] = parts[1] || "eval";
+ parts[3] = subMatch[1];
+ parts[4] = subMatch[2];
+ parts[5] = "";
+ }
+ }
+ let filename = parts[3];
+ let func = parts[1] || UNKNOWN_FUNCTION;
+ [func, filename] = extractSafariExtensionDetails(func, filename);
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
}
};
var init_gecko = __esm(() => {
@@ -79495,17 +80130,17 @@ var init_gecko = __esm(() => {
geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
var init_winjs = __esm(() => {
init_base();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
var init_opera = __esm(() => {
init_base();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
function filenameIsInApp(filename, isNative = false) {
const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
return !isInternal && filename !== undefined && !filename.includes("node_modules/");
@@ -79581,13 +80216,83 @@ var init_node = __esm(() => {
PROMISE_INDEX = /^index \d+$/;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
-function reverseAndStripFrames(stack) {
- if (!stack.length)
- return [];
- const localStack = Array.from(stack);
- localStack.reverse();
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
+function isSameFrame(a, b) {
+ return a.filename === b.filename && a.function === b.function && a.module === b.module && a.lineno === b.lineno && a.colno === b.colno;
+}
+function collapseRepeatedCycle(frames) {
+ for (let length = 1;length <= MAX_REPEATED_CYCLE_LENGTH; length++) {
+ const start = frames.length - 2 * length;
+ if (start < 0)
+ break;
+ let isCycle = true;
+ for (let offset = 0;offset < length; offset++) {
+ const inner = frames[start + offset];
+ if (!isSameFrame(inner, frames[start + length + offset])) {
+ isCycle = false;
+ break;
+ }
+ }
+ if (isCycle) {
+ for (let offset = 0;offset < length; offset++)
+ frames[start + offset] = frames[start + length + offset];
+ frames.length = start + length;
+ return {
+ start,
+ length
+ };
+ }
+ }
+}
+function trimPartialCycle(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ const partialLength = partialCycleLength(frames, cycle);
+ if (partialLength)
+ frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength);
+}
+function innermostPartialCycleLength(frames, cycle) {
+ let partialStart = cycle.start;
+ while (partialStart > 0 && isSameFrame(frames[partialStart - 1], frames[partialStart - 1 + cycle.length]))
+ partialStart--;
+ return cycle.start - partialStart;
+}
+function partialCycleLength(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ let partialEnd = copyEnd;
+ while (partialEnd < frames.length && isSameFrame(frames[partialEnd], frames[partialEnd - cycle.length]))
+ partialEnd++;
+ return partialEnd - copyEnd;
+}
+function survivingFrameCount(frames, cycles) {
+ const innermostCycle = cycles[0];
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0);
+ for (const cycle of cycles)
+ count -= partialCycleLength(frames, cycle);
+ return count;
+}
+function canonicalizeCycleRotation(frames) {
+ const keys = frames.map((frame) => `${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`);
+ let first = 0;
+ for (let i = 1;i < keys.length; i++)
+ if (isSmallerRotation(keys, i, first))
+ first = i;
+ frames.push(...frames.splice(0, first));
+}
+function isSmallerRotation(keys, candidate, best) {
+ for (let offset = 0;offset < keys.length; offset++) {
+ const left = keys[(candidate + offset) % keys.length];
+ const right = keys[(best + offset) % keys.length];
+ if (left !== right)
+ return left < right;
+ }
+ return false;
+}
+function reverseAndStripFrames(stack) {
+ if (!stack.length)
+ return [];
+ const localStack = Array.from(stack);
+ localStack.reverse();
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
...frame,
filename: frame.filename || getLastStackFrame(localStack).filename,
function: frame.function || UNKNOWN_FUNCTION
@@ -79604,7 +80309,9 @@ function createStackParser(platform, ...parsers) {
const frames = [];
const lines = stack.split(`
`);
- for (let i = skipFirstLines;i < lines.length; i++) {
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT);
+ const repeatedCycles = [];
+ for (let i = skipFirstLines;i < endLine; i++) {
const line = lines[i];
if (line.length > 1024)
continue;
@@ -79614,17 +80321,41 @@ function createStackParser(platform, ...parsers) {
const frame = parser(cleanedLine, platform);
if (frame) {
frames.push(frame);
+ const cycle = collapseRepeatedCycle(frames);
+ if (cycle) {
+ for (let i = repeatedCycles.length - 1;i >= 0; i--) {
+ const previous = repeatedCycles[i];
+ if (previous.start + previous.length <= cycle.start)
+ break;
+ repeatedCycles.pop();
+ }
+ repeatedCycles.push(cycle);
+ }
break;
}
}
- if (frames.length >= STACKTRACE_FRAME_LIMIT)
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT)
break;
}
}
+ const sections = [
+ ...repeatedCycles
+ ].sort((a, b) => b.start - a.start);
+ const innermostSection = sections[sections.length - 1];
+ if (innermostSection) {
+ const trimmed = innermostPartialCycleLength(frames, innermostSection);
+ frames.splice(innermostSection.start - trimmed, trimmed);
+ for (const cycle of sections)
+ cycle.start -= trimmed;
+ }
+ for (const cycle of sections)
+ trimPartialCycle(frames, cycle);
+ if (repeatedCycles.some((cycle) => cycle.start === 0 && frames.length === cycle.length))
+ canonicalizeCycleRotation(frames);
return reverseAndStripFrames(frames);
};
}
-var WEBPACK_ERROR_REGEXP, STACKTRACE_FRAME_LIMIT = 50;
+var WEBPACK_ERROR_REGEXP, STACKTRACE_FRAME_LIMIT = 50, MAX_REPEATED_CYCLE_LENGTH = 10, STACKTRACE_LINE_LIMIT = 1000;
var init_parsers = __esm(() => {
init_base();
init_chrome();
@@ -79635,23 +80366,24 @@ var init_parsers = __esm(() => {
WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
var init_dom_exception_coercer = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
class ErrorCoercer {
match(err) {
return isError(err);
}
coerce(err, ctx) {
const stack = this.getStack(err);
- const synthetic = stack === undefined;
+ const replacementStack = stack === undefined ? ctx.syntheticException?.stack : undefined;
+ const synthetic = !!replacementStack;
return {
type: this.getType(err),
value: this.getMessage(err, ctx),
- stack: stack ?? ctx.syntheticException?.stack,
+ stack: stack ?? replacementStack,
cause: err.cause ? ctx.next(err.cause) : undefined,
synthetic
};
@@ -79666,19 +80398,27 @@ class ErrorCoercer {
return String(message);
}
getStack(err) {
- return err.stacktrace || err.stack || undefined;
+ try {
+ const stacktrace = err.stacktrace;
+ if (typeof stacktrace == "string" && stacktrace.length > 0)
+ return stacktrace;
+ const stack = err.stack;
+ return typeof stack == "string" && stack.length > 0 ? stack : undefined;
+ } catch {
+ return;
+ }
}
}
var init_error_coercer = __esm(() => {
init_type_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
var init_error_event_coercer = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
class StringCoercer {
match(input) {
return typeof input == "string";
@@ -79711,7 +80451,7 @@ var init_string_coercer = __esm(() => {
ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
var severityLevels;
var init_types8 = __esm(() => {
severityLevels = [
@@ -79724,7 +80464,7 @@ var init_types8 = __esm(() => {
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
function extractExceptionKeysForMessage(err, maxLength = 40) {
const keys = Object.keys(err);
keys.sort();
@@ -79742,7 +80482,7 @@ function extractExceptionKeysForMessage(err, maxLength = 40) {
}
var init_utils2 = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
class ObjectCoercer {
match(candidate) {
return typeof candidate == "object" && candidate !== null;
@@ -79813,7 +80553,7 @@ var init_object_coercer = __esm(() => {
init_utils2();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
class EventCoercer {
match(err) {
return isEvent(err);
@@ -79833,7 +80573,7 @@ var init_event_coercer = __esm(() => {
init_utils2();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
class PrimitiveCoercer {
match(candidate) {
return isPrimitive(candidate);
@@ -79851,12 +80591,12 @@ var init_primitive_coercer = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
var init_promise_rejection_event = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
var init_coercers = __esm(() => {
init_dom_exception_coercer();
init_error_coercer();
@@ -79868,7 +80608,7 @@ var init_coercers = __esm(() => {
init_promise_rejection_event();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
class ReduceableCache {
constructor(_maxSize) {
this._maxSize = _maxSize;
@@ -79895,7 +80635,7 @@ class ReduceableCache {
}
var init_utils3 = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
var EXCEPTION_STEP_INTERNAL_FIELDS, RESERVED_EXCEPTION_STEP_KEYS;
var init_exception_steps = __esm(() => {
init_utils();
@@ -79909,14 +80649,14 @@ var init_exception_steps = __esm(() => {
]);
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
function getInjectedReleaseId() {
const injected = globalThis._posthogReleaseId;
return typeof injected == "string" && injected.length > 0 ? injected : undefined;
}
var init_release = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/index.mjs
var init_error_tracking = __esm(() => {
init_error_properties_builder();
init_parsers();
@@ -79926,7 +80666,232 @@ var init_error_tracking = __esm(() => {
init_release();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/cookie.mjs
+var init_cookie = __esm(() => {
+ init_utils();
+ init_uuidv7();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
+function getFlagDetailFromFlagAndPayload(key, value, payload) {
+ return {
+ key,
+ enabled: typeof value == "string" ? true : value,
+ variant: typeof value == "string" ? value : undefined,
+ reason: undefined,
+ metadata: {
+ id: undefined,
+ version: undefined,
+ payload: payload ? JSON.stringify(payload) : undefined,
+ description: undefined
+ }
+ };
+}
+var normalizeFlagsResponse = (flagsResponse) => {
+ if ("flags" in flagsResponse) {
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads
+ };
+ }
+ {
+ const featureFlags = flagsResponse.featureFlags ?? {};
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
+ k,
+ parsePayload(v)
+ ]));
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
+ key,
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
+ ]));
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads,
+ flags
+ };
+ }
+}, getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
+ key,
+ getFeatureFlagValue(detail)
+]).filter(([, value]) => value !== undefined)), getPayloadsFromFlags = (flags) => {
+ const safeFlags = flags ?? {};
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
+ const details = safeFlags[flag];
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
+ }).map((flag) => {
+ const payload = safeFlags[flag].metadata?.payload;
+ return [
+ flag,
+ payload ? parsePayload(payload) : undefined
+ ];
+ }));
+}, getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled, parsePayload = (response) => {
+ if (typeof response != "string")
+ return response;
+ try {
+ return JSON.parse(response);
+ } catch {
+ return response;
+ }
+}, MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
+ const minimal = {};
+ const copyKey = (key) => {
+ if (properties[key] !== undefined)
+ minimal[key] = properties[key];
+ };
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
+ transportKeys.forEach(copyKey);
+ return minimal;
+};
+var init_featureFlagUtils = __esm(() => {
+ MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_content",
+ "utm_term",
+ "gad_source",
+ "mc_cid",
+ "gclid",
+ "gclsrc",
+ "dclid",
+ "gbraid",
+ "wbraid",
+ "fbclid",
+ "msclkid",
+ "twclid",
+ "li_fat_id",
+ "igshid",
+ "ttclid",
+ "rdt_cid",
+ "epik",
+ "qclid",
+ "sccid",
+ "irclid",
+ "_kx"
+ ];
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
+ "$feature_flag",
+ "$feature_flag_response",
+ "$feature_flag_has_experiment",
+ "$feature_flag_id",
+ "$feature_flag_version",
+ "$feature_flag_reason",
+ "$feature_flag_request_id",
+ "$feature_flag_evaluated_at",
+ "$feature_flag_error",
+ "locally_evaluated",
+ "$groups",
+ "$process_person_profile",
+ "$geoip_disable",
+ "$current_url",
+ "$pathname",
+ "$referring_domain",
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
+ "$session_id",
+ "$window_id",
+ "$lib",
+ "$lib_version",
+ "$device_id",
+ "$is_server"
+ ];
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
+class SimpleEventEmitter {
+ constructor() {
+ this.events = {};
+ this.events = {};
+ }
+ on(event, listener) {
+ if (!this.events[event])
+ this.events[event] = [];
+ this.events[event].push(listener);
+ return () => {
+ this.events[event] = this.events[event].filter((x) => x !== listener);
+ };
+ }
+ emit(event, payload) {
+ for (const listener of this.events[event] || [])
+ listener(payload);
+ for (const listener of this.events["*"] || [])
+ listener(event, payload);
+ }
+}
+var init_eventemitter = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
+function isGzipSupported() {
+ return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+}
+async function gzipCompress(input, isDebug = true, options) {
+ try {
+ const inputBytes = new TextEncoder().encode(input);
+ const compressedStream = new globalThis.CompressionStream("gzip");
+ const writer = compressedStream.writable.getWriter();
+ const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
+ try {
+ await writer.abort(err);
+ } catch {}
+ throw err;
+ });
+ const responsePromise = new Response(compressedStream.readable).blob();
+ const [compressed] = await Promise.all([
+ responsePromise,
+ writePromise
+ ]);
+ await validateNativeGzip(compressed, inputBytes);
+ return compressed;
+ } catch (error) {
+ if (options?.rethrow)
+ throw error;
+ if (isDebug)
+ console.error("Failed to gzip compress data", error);
+ return null;
+ }
+}
+var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError", GZIP_MAGIC_FIRST_BYTE = 31, GZIP_MAGIC_SECOND_BYTE = 139, GZIP_DEFLATE_METHOD = 8, hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE, crc32Table, getCrc32Table = () => {
+ if (crc32Table)
+ return crc32Table;
+ crc32Table = [];
+ for (let i = 0;i < 256; i++) {
+ let crc = i;
+ for (let j = 0;j < 8; j++)
+ crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
+ crc32Table[i] = crc >>> 0;
+ }
+ return crc32Table;
+}, crc32 = (bytes) => {
+ const table = getCrc32Table();
+ let crc = 4294967295;
+ for (let i = 0;i < bytes.length; i++)
+ crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
+ return (4294967295 ^ crc) >>> 0;
+}, throwNativeGzipValidationError = (reason) => {
+ throw createNamedError(NATIVE_GZIP_VALIDATION_ERROR, `Native gzip produced invalid output: ${reason}`);
+}, validateNativeGzip = async (compressed, inputBytes) => {
+ if (compressed.size < 18)
+ throwNativeGzipValidationError("too-short");
+ const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
+ if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
+ throwNativeGzipValidationError("invalid-header");
+ const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
+ if (trailer.getUint32(0, true) !== crc32(inputBytes))
+ throwNativeGzipValidationError("invalid-crc");
+ const inputSize = inputBytes.length >>> 0;
+ if (trailer.getUint32(4, true) !== inputSize)
+ throwNativeGzipValidationError("invalid-size");
+};
+var init_gzip = __esm(() => {
+ init_types7();
+ init_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
async function logFlushError(err) {
if (err instanceof PostHogFetchHttpError) {
let text = "";
@@ -79956,6 +80921,17 @@ function isRetryableFlagsFetchError(err) {
const code = cause?.code ?? cause?.cause?.code;
return code !== "ECONNREFUSED";
}
+function byteLengthOf(body) {
+ try {
+ if (typeof body != "string")
+ return body instanceof Uint8Array ? body.byteLength : body.size;
+ if ("u" > typeof Buffer)
+ return Buffer.byteLength(body, STRING_FORMAT);
+ return new TextEncoder().encode(body).length;
+ } catch {
+ return 0;
+ }
+}
function isPostHogFetchContentTooLargeError(err) {
return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
}
@@ -79982,6 +80958,7 @@ class PostHogCoreStateless {
new PrimitiveCoercer
], createDefaultStackParser());
}
+ getEvaluationRuntime() {}
constructor(apiKey, options = {}) {
this.flushPromise = null;
this.pendingFlushPromise = null;
@@ -80230,6 +81207,9 @@ class PostHogCoreStateless {
requestData.$device_id = personProperties.$device_id;
if (this.evaluationContexts && this.evaluationContexts.length > 0)
requestData.evaluation_contexts = this.evaluationContexts;
+ const evaluationRuntime = this.getEvaluationRuntime();
+ if (evaluationRuntime)
+ requestData.evaluation_runtime = evaluationRuntime;
const fetchOptions = {
method: "POST",
headers: {
@@ -80545,10 +81525,13 @@ class PostHogCoreStateless {
flushBackground() {
if (this.pendingFlushPromise)
return;
- this.flush().catch(async (err) => {
+ this.flushAutomatic().catch(async (err) => {
await logFlushError(err);
});
}
+ flushAutomatic() {
+ return this.flush();
+ }
async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
let iteration = 0;
@@ -80725,352 +81708,3054 @@ class PostHogCoreStateless {
sentFromRoute += batchMessages.length;
}
}
- async _sendLogsBatch(payload) {
- if (this.disabled)
+ async _sendOtlpBatch({ path, auth, payload }) {
+ if (this.disabled)
+ return {
+ kind: "fatal",
+ error: new Error("The client is disabled")
+ };
+ let serialized;
+ try {
+ serialized = JSON.stringify(payload);
+ } catch (error) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Could not serialize a ${path} batch; reporting it as too large`, error));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const payloadBytes = byteLengthOf(serialized);
+ if (payloadBytes > OTLP_MAX_BODY_BYTES) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Not sending a ${path} batch of ${payloadBytes} bytes: the endpoint accepts at most ${OTLP_MAX_BODY_BYTES}`));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const url = auth === "bearer" ? `${this.host}/i/v1/${path}` : `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
+ const body = gzippedPayload || serialized;
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json",
+ ...auth === "bearer" && {
+ Authorization: `Bearer ${this.apiKey}`
+ },
+ ...gzippedPayload !== null && {
+ "Content-Encoding": "gzip"
+ }
+ },
+ body
+ };
+ try {
+ await this.fetchWithRetry(url, fetchOptions, {
+ type: "successful-write"
+ }, {
+ retryCheck: (err) => {
+ if (isPostHogFetchContentTooLargeError(err))
+ return false;
+ if (err instanceof PostHogFetchHttpError && err.retryAfterMs !== undefined)
+ return false;
+ return isPostHogFetchRetryableError(err);
+ }
+ });
+ return {
+ kind: "ok"
+ };
+ } catch (err) {
+ if (isPostHogFetchContentTooLargeError(err))
+ return {
+ kind: "too-large"
+ };
+ if (isPostHogFetchRetryableError(err)) {
+ const retryAfterMs = err instanceof PostHogFetchHttpError ? err.retryAfterMs : undefined;
+ return {
+ kind: "retry-later",
+ error: err,
+ ...retryAfterMs !== undefined && {
+ retryAfterMs
+ }
+ };
+ }
+ return {
+ kind: "fatal",
+ error: err
+ };
+ }
+ }
+ async _sendLogsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "logs",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendMetricsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "metrics",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendTracesBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "traces",
+ auth: "bearer",
+ payload
+ });
+ }
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
+ const body = options.body ? options.body : "";
+ const reqByteLength = byteLengthOf(body);
+ const retriableOptions = {
+ ...this._retryOptions,
+ ...retryOptions
+ };
+ let attempt = 0;
+ return await retriable(async () => {
+ attempt++;
+ const ctrl = new AbortController;
+ const timeoutMs = requestTimeout ?? this.requestTimeout;
+ const requestDeadline = Date.now() + timeoutMs;
+ let timer;
+ const deadline = new Promise((_resolve, reject) => {
+ timer = safeSetTimeout(() => {
+ const timeoutError = createNamedError("AbortError", `Request timed out after ${timeoutMs}ms`);
+ reject(timeoutError);
+ ctrl.abort(timeoutError);
+ }, timeoutMs);
+ });
+ let res;
+ let responseAccepted = false;
+ let cancellation;
+ const cancelBody = () => cancellation ??= (async () => {
+ try {
+ await res?.body?.cancel();
+ } catch {}
+ })();
+ try {
+ let fetchPromise;
+ try {
+ fetchPromise = this.fetch(url, {
+ signal: ctrl.signal,
+ ...options
+ });
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ fetchPromise.then((lateResponse) => {
+ if (ctrl.signal.aborted && !responseAccepted)
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
+ }).catch(() => {});
+ try {
+ res = await Promise.race([
+ fetchPromise,
+ deadline
+ ]);
+ responseAccepted = true;
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ const isNoCors = options.mode === "no-cors";
+ const maxSuccessStatus = responseHandling.type === "successful-write" ? 300 : 400;
+ if (!isNoCors && (res.status < 200 || res.status >= maxSuccessStatus))
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
+ if (responseHandling.type === "successful-write") {
+ try {
+ await Promise.race([
+ cancelBody(),
+ deadline
+ ]);
+ } catch {}
+ return;
+ }
+ try {
+ return await Promise.race([
+ responseHandling.consume(res),
+ deadline
+ ]);
+ } catch (e) {
+ if (ctrl.signal.aborted)
+ throw new PostHogFetchNetworkError(e);
+ throw e;
+ }
+ } finally {
+ clearTimeout(timer);
+ if (ctrl.signal.aborted && res)
+ cancelBody();
+ }
+ }, {
+ ...retriableOptions,
+ retryCheck: (error) => {
+ const shouldRetry = retriableOptions.retryCheck(error);
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
+ error.cancelResponseBody();
+ return shouldRetry;
+ }
+ });
+ }
+ async _shutdown(shutdownTimeoutMs = 30000) {
+ await this._initPromise;
+ let hasTimedOut = false;
+ this.clearFlushTimer();
+ if (this.disabled)
+ return;
+ const doShutdown = async () => {
+ try {
+ await this.promiseQueue.join();
+ while (true) {
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
+ if (!hasQueuedEvents)
+ break;
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
+ await this.flush();
+ if (hasTimedOut)
+ break;
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
+ break;
+ }
+ }
+ } catch (e) {
+ if (!isPostHogFetchError(e))
+ throw e;
+ await logFlushError(e);
+ }
+ };
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
+ shutdownTimeoutMs
+ });
+ hasTimedOut = true;
+ });
+ }
+ async shutdown(shutdownTimeoutMs = 30000) {
+ if (this.shutdownPromise)
+ this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
+ else
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
+ this.shutdownPromise = null;
+ });
+ return this.shutdownPromise;
+ }
+}
+var PostHogFetchHttpError, PostHogFetchNetworkError, applyCallerFeatureFlagOverrides = (target, callerProperties) => {
+ for (const key of Object.keys(callerProperties))
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
+ target[key] = callerProperties[key];
+}, OTLP_MAX_BODY_BYTES = 10485760, DEFAULT_QUEUE_ROUTE = "default";
+var init_posthog_core_stateless = __esm(() => {
+ init_eventemitter();
+ init_featureFlagUtils();
+ init_gzip();
+ init_types7();
+ init_utils();
+ init_retry_after();
+ init_uuidv7();
+ init_error_tracking();
+ PostHogFetchHttpError = class PostHogFetchHttpError extends Error {
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
+ }
+ get status() {
+ return this.response.status;
+ }
+ get retryAfterMs() {
+ try {
+ return parseRetryAfterMs(this.response.headers?.get("retry-after"));
+ } catch {
+ return;
+ }
+ }
+ get bodyReadTimedOut() {
+ return this._bodyReadTimedOut;
+ }
+ get text() {
+ if (!this.responseBodyTextPromise)
+ if (Date.now() >= this.responseBodyDeadline) {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ this.cancelResponseBody(timeoutError);
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
+ } else {
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
+ this.responseBodyTimer = safeSetTimeout(() => {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ reject(timeoutError);
+ this.cancelResponseBody(timeoutError);
+ }, this.responseBodyDeadline - Date.now());
+ });
+ let responseBodyText;
+ try {
+ responseBodyText = Promise.resolve(this.response.text());
+ } catch (error) {
+ responseBodyText = Promise.reject(error);
+ }
+ this.responseBodyTextPromise = Promise.race([
+ responseBodyText,
+ responseBodyTimeout
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
+ }
+ return this.responseBodyTextPromise;
+ }
+ get json() {
+ return this.text.then((text) => JSON.parse(text));
+ }
+ cancelResponseBody(reason) {
+ clearTimeout(this.responseBodyTimer);
+ if (!this.abortController.signal.aborted)
+ this.abortController.abort(reason);
+ (async () => {
+ try {
+ await this.response.body?.cancel();
+ } catch {}
+ })();
+ }
+ };
+ PostHogFetchNetworkError = class PostHogFetchNetworkError extends Error {
+ constructor(error) {
+ super("Network error while fetching PostHog", error instanceof Error ? {
+ cause: error
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+ }
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core.mjs
+var init_posthog_core = __esm(() => {
+ init_featureFlagUtils();
+ init_types7();
+ init_posthog_core_stateless();
+ init_uuidv7();
+ init_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/tracing-headers.mjs
+var init_tracing_headers = __esm(() => {
+ init_type_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.mjs
+function isTruthyOrFalsyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return true;
+ if (typeof value == "string") {
+ const lowercaseValue = value.toLowerCase();
+ return lowercaseValue === "true" || lowercaseValue === "false";
+ }
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyOrFalsyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function isTruthyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return value;
+ if (typeof value == "string")
+ return value.toLowerCase() === "true";
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function assertUnicodeScalarString(value) {
+ for (let index = 0;index < value.length; index++) {
+ const unit = value.charCodeAt(index);
+ if (unit >= 55296 && unit <= 56319) {
+ const next = value.charCodeAt(index + 1);
+ if (index + 1 >= value.length || next < 56320 || next > 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ index++;
+ } else if (unit >= 56320 && unit <= 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ }
+}
+function assertJsonRepresentable(value, seen = new Set) {
+ if (value === null || typeof value == "boolean")
+ return;
+ if (typeof value == "string")
+ return void assertUnicodeScalarString(value);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot represent non-finite number ${value} like the flags service`);
+ return;
+ }
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular array during local evaluation");
+ seen.add(value);
+ try {
+ for (let index = 0;index < value.length; index++)
+ if (index in value)
+ assertJsonRepresentable(value[index], seen);
+ } finally {
+ seen.delete(value);
+ }
+ return;
+ }
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot represent a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular object during local evaluation");
+ seen.add(value);
+ try {
+ for (const key of Object.keys(value)) {
+ assertUnicodeScalarString(key);
+ assertJsonRepresentable(value[key], seen);
+ }
+ } finally {
+ seen.delete(value);
+ }
+ return;
+ }
+ throw new InconclusiveMatchError(`Cannot represent ${typeof value} like the flags service`);
+}
+function compareJsonObjectKeys(left, right) {
+ let leftIndex = 0;
+ let rightIndex = 0;
+ while (leftIndex < left.length && rightIndex < right.length) {
+ const leftUnit = left.charCodeAt(leftIndex);
+ const rightUnit = right.charCodeAt(rightIndex);
+ const leftIsHighSurrogate = leftUnit >= 55296 && leftUnit <= 56319;
+ const rightIsHighSurrogate = rightUnit >= 55296 && rightUnit <= 56319;
+ const leftNext = leftIsHighSurrogate ? left.charCodeAt(leftIndex + 1) : 0;
+ const rightNext = rightIsHighSurrogate ? right.charCodeAt(rightIndex + 1) : 0;
+ const leftCodePoint = leftIsHighSurrogate ? (leftUnit - 55296) * 1024 + leftNext - 56320 + 65536 : leftUnit;
+ const rightCodePoint = rightIsHighSurrogate ? (rightUnit - 55296) * 1024 + rightNext - 56320 + 65536 : rightUnit;
+ if (leftCodePoint !== rightCodePoint)
+ return leftCodePoint - rightCodePoint;
+ leftIndex += leftIsHighSurrogate ? 2 : 1;
+ rightIndex += rightIsHighSurrogate ? 2 : 1;
+ }
+ return left.length - right.length;
+}
+function serializeJsonValue(value, seen = new Set) {
+ if (value === null)
+ return "null";
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return JSON.stringify(value);
+ }
+ if (typeof value == "boolean")
+ return value ? "true" : "false";
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot stringify non-finite number ${value} like the flags service`);
+ if (Number.isInteger(value))
+ throw new InconclusiveMatchError(`Cannot distinguish integer ${value} from an integral JSON float during local evaluation`);
+ return String(value);
+ }
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular array during local evaluation");
+ seen.add(value);
+ try {
+ const items = [];
+ for (let index = 0;index < value.length; index++)
+ items.push(index in value ? serializeJsonValue(value[index], seen) : "null");
+ return `[${items.join(",")}]`;
+ } finally {
+ seen.delete(value);
+ }
+ }
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot stringify a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular object during local evaluation");
+ seen.add(value);
+ try {
+ const keys = Object.keys(value);
+ keys.forEach(assertUnicodeScalarString);
+ return `{${keys.sort(compareJsonObjectKeys).map((key) => `${JSON.stringify(key)}:${serializeJsonValue(value[key], seen)}`).join(",")}}`;
+ } finally {
+ seen.delete(value);
+ }
+ }
+ throw new InconclusiveMatchError(`Cannot stringify ${typeof value} like the flags service`);
+}
+function exactMatchString(value) {
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return value;
+ }
+ return serializeJsonValue(value);
+}
+function isValidRegex(regex) {
+ try {
+ new RegExp(regex);
+ return true;
+ } catch {
+ return false;
+ }
+}
+function asciiLowercase(value) {
+ return String(value).replace(/[A-Z]/g, (character) => character.toLowerCase());
+}
+function parseSemverNumericIdentifier(part, raw, parsingPolicy) {
+ if (!/^\d+$/.test(part) || parsingPolicy === "strict" && part.length > 1 && part[0] === "0")
+ throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
+ return parseInt(part, 10);
+}
+function parseFeatureFlagSemver(value, parsingPolicy = "strict") {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const baseVersion = text.split("-")[0].split("+")[0];
+ if (!baseVersion || baseVersion.startsWith("."))
+ throw new InconclusiveMatchError(`Invalid semver: ${value}`);
+ const parts = baseVersion.split(".");
+ const parsePart = (part) => {
+ if (part === undefined || part === "")
+ return 0;
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
+ };
+ return [
+ parsePart(parts[0]),
+ parsePart(parts[1]),
+ parsePart(parts[2])
+ ];
+}
+function compareSemverTuples(a, b) {
+ for (let i = 0;i < 3; i++) {
+ if (a[i] < b[i])
+ return -1;
+ if (a[i] > b[i])
+ return 1;
+ }
+ return 0;
+}
+function computeTildeBounds(value, parsingPolicy) {
+ const parsed = parseFeatureFlagSemver(value, parsingPolicy);
+ return {
+ lower: [
+ parsed[0],
+ parsed[1],
+ parsed[2]
+ ],
+ upper: [
+ parsed[0],
+ parsed[1] + 1,
+ 0
+ ]
+ };
+}
+function computeCaretBounds(value, parsingPolicy) {
+ const [major, minor, patch] = parseFeatureFlagSemver(value, parsingPolicy);
+ const lower = [
+ major,
+ minor,
+ patch
+ ];
+ let upper;
+ upper = major > 0 ? [
+ major + 1,
+ 0,
+ 0
+ ] : minor > 0 ? [
+ 0,
+ minor + 1,
+ 0
+ ] : [
+ 0,
+ 0,
+ patch + 1
+ ];
+ return {
+ lower,
+ upper
+ };
+}
+function computeWildcardBounds(value, parsingPolicy) {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
+ if (!cleanedText)
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ const parts = cleanedText.split(".");
+ const parseWildcardPart = (part) => {
+ if (parsingPolicy === "legacy-permissive") {
+ const parsed = parseInt(part, 10);
+ if (!isNaN(parsed))
+ return parsed;
+ } else
+ try {
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
+ } catch {}
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ };
+ const major = parseWildcardPart(parts[0]);
+ if (parts.length === 1)
+ return {
+ lower: [
+ major,
+ 0,
+ 0
+ ],
+ upper: [
+ major + 1,
+ 0,
+ 0
+ ]
+ };
+ const minor = parseWildcardPart(parts[1]);
+ return {
+ lower: [
+ major,
+ minor,
+ 0
+ ],
+ upper: [
+ major,
+ minor + 1,
+ 0
+ ]
+ };
+}
+function convertToDateTime(value) {
+ if (value instanceof Date)
+ return value;
+ if (typeof value == "string" || typeof value == "number") {
+ const date = new Date(value);
+ if (!isNaN(date.valueOf()))
+ return date;
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
+ }
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
+}
+function relativeDateParseForFeatureFlagMatching(value) {
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
+ const match = value.match(regex);
+ const parsedDt = new Date(new Date().toISOString());
+ if (!match || !match.groups)
+ return null;
+ const number = parseInt(match.groups["number"]);
+ if (number >= 1e4)
+ return null;
+ const interval = match.groups["interval"];
+ if (interval === "h")
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
+ else if (interval === "d")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
+ else if (interval === "w")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
+ else if (interval === "m")
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
+ else {
+ if (interval !== "y")
+ return null;
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
+ }
+ return parsedDt;
+}
+function matchFeatureFlagProperty(property, propertyValues, options = {}) {
+ const key = property.key;
+ const value = property.value;
+ const operator = property.operator || "exact";
+ const parsingPolicy = options.semverParsingPolicy ?? "strict";
+ const hasProperty = Object.prototype.hasOwnProperty.call(propertyValues, key);
+ if (hasProperty) {
+ if (operator === "is_not_set")
+ return false;
+ else if (operator === "is_set")
+ return true;
+ } else
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
+ const overrideValue = propertyValues[key];
+ if (overrideValue === undefined) {
+ options.warnFunction?.(`Property ${key} cannot have a value of undefined with the ${operator} operator`);
+ return operator === "is_not";
+ }
+ if (overrideValue === null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator) && operator !== "exact" && operator !== "is_not") {
+ options.warnFunction?.(`Property ${key} cannot have a value of null with the ${operator} operator`);
+ return false;
+ }
+ const computeExactMatch = (target, actual) => {
+ if (isTruthyOrFalsyPropertyValue(target)) {
+ assertJsonRepresentable(actual);
+ return isTruthyPropertyValue(target) === isTruthyPropertyValue(actual);
+ }
+ if (Array.isArray(target)) {
+ const actualString = exactMatchString(actual).toLowerCase();
+ return target.some((item) => exactMatchString(item).toLowerCase() === actualString);
+ }
+ return exactMatchString(target).toLowerCase() === exactMatchString(actual).toLowerCase();
+ };
+ const compare = (lhs, rhs, comparisonOperator) => {
+ if (comparisonOperator === "gt")
+ return lhs > rhs;
+ if (comparisonOperator === "gte")
+ return lhs >= rhs;
+ if (comparisonOperator === "lt")
+ return lhs < rhs;
+ if (comparisonOperator === "lte")
+ return lhs <= rhs;
+ throw new Error(`Invalid operator: ${comparisonOperator}`);
+ };
+ switch (operator) {
+ case "exact":
+ return computeExactMatch(value, overrideValue);
+ case "is_not":
+ return !computeExactMatch(value, overrideValue);
+ case "is_set":
+ return true;
+ case "icontains":
+ return asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "not_icontains":
+ return !asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "starts_with":
+ return asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "not_starts_with":
+ return !asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "ends_with":
+ return asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "not_ends_with":
+ return !asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
+ case "not_regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
+ case "gt":
+ case "gte":
+ case "lt":
+ case "lte": {
+ const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
+ const parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : 0 / 0;
+ if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
+ return compare(parsedOverride, parsedValue, operator);
+ return compare(String(overrideValue), String(value), operator);
+ }
+ case "is_date_after":
+ case "is_date_before": {
+ if (typeof value == "boolean")
+ throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
+ if (parsedDate == null)
+ parsedDate = convertToDateTime(value);
+ const overrideDate = convertToDateTime(overrideValue);
+ return operator === "is_date_before" ? overrideDate < parsedDate : overrideDate > parsedDate;
+ }
+ case "semver_eq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) === 0;
+ case "semver_neq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) !== 0;
+ case "semver_gt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) > 0;
+ case "semver_gte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) >= 0;
+ case "semver_lt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) < 0;
+ case "semver_lte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) <= 0;
+ case "semver_tilde": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeTildeBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_caret": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeCaretBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_wildcard": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeWildcardBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ default:
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
+ }
+}
+async function hashSHA1(text) {
+ const subtle = globalThis.crypto?.subtle;
+ if (!subtle)
+ throw new Error("SubtleCrypto API not available");
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
+ return Array.from(new Uint8Array(hashBuffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
+}
+async function getFeatureFlagHash(key, bucketingValue, salt = "") {
+ const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
+}
+function getFeatureFlagVariantLookupTable(variants) {
+ const table = [];
+ let valueMin = 0;
+ for (const variant of variants) {
+ const valueMax = valueMin + variant.rollout_percentage / 100;
+ table.push({
+ valueMin,
+ valueMax,
+ key: variant.key
+ });
+ valueMin = valueMax;
+ }
+ return table;
+}
+async function getFeatureFlagVariant(key, bucketingValue, variants) {
+ const hashValue = await getFeatureFlagHash(key, bucketingValue, "variant");
+ return getFeatureFlagVariantLookupTable(variants).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax)?.key;
+}
+function resolveFeatureFlagPayload(payloads, flagValue) {
+ if (flagValue === false || flagValue == null || !payloads)
+ return null;
+ const payloadKey = typeof flagValue == "boolean" ? flagValue.toString() : flagValue;
+ const payload = payloads[payloadKey] || null;
+ return payload == null ? null : parsePayload(payload);
+}
+var NULL_VALUES_ALLOWED_OPERATORS, LONG_SCALE = 1152921504606847000, InconclusiveMatchError;
+var init_featureFlagLocalEvaluation = __esm(() => {
+ init_featureFlagUtils();
+ NULL_VALUES_ALLOWED_OPERATORS = [
+ "is_not",
+ "is_set"
+ ];
+ InconclusiveMatchError = class InconclusiveMatchError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = this.constructor.name;
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
+ }
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-any-value.mjs
+function newState() {
+ return {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ };
+}
+function toOtlpKeyValueList(attrs, logger) {
+ try {
+ return encodeKeyValueList(attrs, logger, newState(), 0);
+ } catch {
+ return [];
+ }
+}
+function encodeBigInt(value, logger) {
+ const decimal = value.toString();
+ const limit = BigInt(INT64_RANGE_LIMIT_DECIMAL);
+ if (value >= limit || value < -limit) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
+ };
+ }
+ return {
+ intValue: decimal
+ };
+}
+function encodeAnyValue(value, logger, state, depth) {
+ if (state.remainingNodes <= 0)
+ return {
+ stringValue: TRUNCATED_VALUE
+ };
+ state.remainingNodes--;
+ if (isBoolean(value))
+ return {
+ boolValue: value
+ };
+ if (typeof value == "bigint")
+ return encodeBigInt(value, logger);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ return {
+ stringValue: String(value)
+ };
+ if (Number.isInteger(value)) {
+ if (Number.isSafeInteger(value))
+ return {
+ intValue: String(value)
+ };
+ if ("u" < typeof BigInt)
+ return {
+ stringValue: String(value)
+ };
+ const decimal = BigInt(value).toString();
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
+ };
+ }
+ return {
+ intValue: decimal
+ };
+ }
+ return {
+ doubleValue: value
+ };
+ }
+ if (typeof value == "string")
+ return {
+ stringValue: sanitizeString(value)
+ };
+ if (typeof value == "function")
+ return {
+ stringValue: FUNCTION_VALUE
+ };
+ if (typeof value == "symbol")
+ return {
+ stringValue: String(value)
+ };
+ if (typeof value == "object" && value !== null) {
+ if (state.ancestors.has(value))
+ return {
+ stringValue: CIRCULAR_VALUE
+ };
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return {
+ stringValue: TRUNCATED_VALUE
+ };
+ if (value instanceof Date) {
+ const time = value.getTime();
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
+ return {
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ };
+ }
+ state.ancestors.add(value);
+ try {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
+ return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
+ } catch {}
+ if (isArray(value))
+ return {
+ arrayValue: {
+ values: encodeArrayValues(value, logger, state, depth + 1)
+ }
+ };
+ return {
+ kvlistValue: {
+ values: encodeKeyValueList(value, logger, state, depth + 1)
+ }
+ };
+ } finally {
+ state.ancestors.delete(value);
+ }
+ }
+ return {
+ stringValue: sanitizeString(String(value))
+ };
+}
+function encodeArrayValues(values, logger, state, depth) {
+ const result = [];
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ let index = 0;
+ for (;index < itemCount && state.remainingNodes > 0; index++)
+ try {
+ const element = index in values ? values[index] : undefined;
+ if (isNullish(element))
+ continue;
+ result.push(encodeAnyValue(element, logger, state, depth));
+ } catch {
+ result.push({
+ stringValue: UNSERIALIZABLE_VALUE
+ });
+ }
+ if (values.length > index)
+ result.push({
+ stringValue: TRUNCATED_VALUE
+ });
+ return result;
+}
+function encodeKeyValueList(attrs, logger, state, depth) {
+ const result = [];
+ for (const key in attrs)
+ if (propertyIsEnumerable.call(attrs, key)) {
+ if (!key) {
+ logger?.debug("Dropping an attribute with an empty key");
+ continue;
+ }
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
+ logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
+ break;
+ }
+ try {
+ const value = attrs[key];
+ if (isNull(value) || isUndefined(value))
+ continue;
+ result.push({
+ key: sanitizeString(key),
+ value: encodeAnyValue(value, logger, state, depth)
+ });
+ } catch {
+ result.push({
+ key: sanitizeString(key),
+ value: {
+ stringValue: UNSERIALIZABLE_VALUE
+ }
+ });
+ }
+ }
+ return result;
+}
+var INT64_RANGE_LIMIT = 9223372036854776000, INT64_RANGE_LIMIT_DECIMAL = "9223372036854775808", propertyIsEnumerable;
+var init_otlp_any_value = __esm(() => {
+ init_type_utils();
+ init_json_utils();
+ propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-resource.mjs
+function buildOtlpResourceAttributes(config, sdkName, sdkVersion) {
+ return {
+ ...assignUserAttributes({}, config.resourceAttributes),
+ "service.name": config.serviceName || "unknown_service",
+ ...config.environment && {
+ "deployment.environment": config.environment
+ },
+ ...config.serviceVersion && {
+ "service.version": config.serviceVersion
+ },
+ "telemetry.sdk.name": sdkName,
+ "telemetry.sdk.version": sdkVersion
+ };
+}
+function toOtlpResourceKeyValueList(attributes, logger) {
+ const user = assignUserAttributes({}, attributes);
+ const sdk = {};
+ for (const key of SDK_RESOURCE_KEYS)
+ if (Object.prototype.hasOwnProperty.call(user, key)) {
+ sdk[key] = user[key];
+ delete user[key];
+ }
+ return [
+ ...toOtlpKeyValueList(user, logger),
+ ...toOtlpKeyValueList(sdk, logger)
+ ];
+}
+function normalizeOsName(name) {
+ if (!name)
+ return;
+ return Object.prototype.hasOwnProperty.call(OS_NAMES, name) ? OS_NAMES[name] : name;
+}
+function osResourceAttributes(name, version) {
+ const osName = normalizeOsName(name);
+ return {
+ ...osName ? {
+ "os.name": osName
+ } : {},
+ ...version ? {
+ "os.version": version
+ } : {}
+ };
+}
+var SDK_RESOURCE_KEYS, OS_NAMES;
+var init_otlp_resource = __esm(() => {
+ init_json_utils();
+ init_otlp_any_value();
+ SDK_RESOURCE_KEYS = [
+ "service.name",
+ "deployment.environment",
+ "service.version",
+ "telemetry.sdk.name",
+ "telemetry.sdk.version"
+ ];
+ OS_NAMES = {
+ darwin: "macOS",
+ win32: "Windows",
+ cygwin: "Windows",
+ linux: "Linux",
+ android: "Android",
+ freebsd: "FreeBSD",
+ openbsd: "OpenBSD",
+ netbsd: "NetBSD",
+ sunos: "SunOS",
+ aix: "AIX",
+ haiku: "Haiku",
+ "Mac OS X": "macOS"
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
+var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY;
+var init_logs_utils = __esm(() => {
+ init_utils();
+ init_json_utils();
+ init_otlp_any_value();
+ init_otlp_resource();
+ OTLP_SEVERITY_MAP = {
+ trace: {
+ text: "TRACE",
+ number: 1
+ },
+ debug: {
+ text: "DEBUG",
+ number: 5
+ },
+ info: {
+ text: "INFO",
+ number: 9
+ },
+ warn: {
+ text: "WARN",
+ number: 13
+ },
+ error: {
+ text: "ERROR",
+ number: 17
+ },
+ fatal: {
+ text: "FATAL",
+ number: 21
+ }
+ };
+ DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/flush-timer.mjs
+class FlushTimer {
+ constructor(_onFire) {
+ this._onFire = _onFire;
+ this._firesAt = 0;
+ }
+ get pending() {
+ return !!this._timer;
+ }
+ arm(delayMs) {
+ this.clear();
+ this._firesAt = Date.now() + delayMs;
+ this._timer = safeSetTimeout(() => {
+ this._timer = undefined;
+ this._onFire();
+ }, delayMs);
+ }
+ armNoEarlierThan(delayMs) {
+ if (this._timer && Date.now() + delayMs <= this._firesAt)
+ return;
+ this.arm(delayMs);
+ }
+ clear() {
+ if (this._timer) {
+ clearTimeout(this._timer);
+ this._timer = undefined;
+ }
+ }
+}
+var init_flush_timer = __esm(() => {
+ init_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/backoff.mjs
+function drawJitter() {
+ return 1 - JITTER + Math.random() * JITTER * 2;
+}
+function backoffDelayMs(baseMs, failures, jitter, maxMs) {
+ const exponent = Math.min(Math.max(0, failures - 1), MAX_FLUSH_BACKOFF_EXPONENT);
+ const delay = baseMs * 2 ** exponent;
+ const capped = maxMs === undefined ? delay : Math.min(delay, Math.max(maxMs, baseMs));
+ return Math.round(capped * jitter);
+}
+var MAX_FLUSH_BACKOFF_EXPONENT = 6, MAX_FLUSH_BACKOFF_MS = 30000, JITTER = 0.25, NO_JITTER = 1;
+var init_backoff = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/index.mjs
+var init_logs = __esm(() => {
+ init_logs_utils();
+ init_types7();
+ init_utils();
+ init_flush_timer();
+ init_retry_after();
+ init_backoff();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
+function msToUnixNano(ms) {
+ return String(ms) + "000000";
+}
+function seriesKey(type, name, unit, attributes) {
+ let attrsKey = "";
+ if (attributes) {
+ const keys = Object.keys(attributes).sort();
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
+ }
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
+}
+function bucketIndexFor(value, bounds) {
+ for (let i = 0;i < bounds.length; i++)
+ if (value <= bounds[i])
+ return i;
+ return bounds.length;
+}
+function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
+ return buildOtlpResourceAttributes(config, scopeName, scopeVersion);
+}
+function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
+ return {
+ resourceMetrics: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes)
+ },
+ scopeMetrics: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ metrics
+ }
+ ]
+ }
+ ]
+ };
+}
+var DEFAULT_HISTOGRAM_BOUNDS;
+var init_metrics_utils = __esm(() => {
+ init_otlp_resource();
+ DEFAULT_HISTOGRAM_BOUNDS = [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 75,
+ 100,
+ 250,
+ 500,
+ 750,
+ 1000,
+ 2500,
+ 5000,
+ 7500,
+ 1e4
+ ];
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
+function resolveMetricsConfig(config) {
+ const resourceAttributes = config?.resourceAttributes;
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSend: config?.beforeSend,
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
+ };
+}
+var DEFAULT_FLUSH_INTERVAL_MS = 1e4, DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
+var init_config2 = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
+class PostHogMetrics {
+ constructor(_instance, _config, _logger) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._series = new Map;
+ this._flushTimer = new FlushTimer(() => this.flush().catch((e) => {
+ this._logger.error("Metrics flush failed:", e);
+ }));
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ this._retryAfter = new RetryAfterWindow;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._generation = 0;
+ }
+ count(name, value = 1, options) {
+ this._capture({
+ name,
+ type: "count",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
+ });
+ }
+ gauge(name, value, options) {
+ this._capture({
+ name,
+ type: "gauge",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
+ });
+ }
+ histogram(name, value, options) {
+ this._capture({
+ name,
+ type: "histogram",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
+ });
+ }
+ flush() {
+ const prev = this._flushPromise;
+ const run = async () => {
+ if (prev)
+ await prev.catch(() => {});
+ await this._doFlush();
+ };
+ const p = run().finally(() => {
+ if (this._flushPromise === p)
+ this._flushPromise = null;
+ });
+ this._flushPromise = p;
+ return p;
+ }
+ drainWindow() {
+ if (this._series.size === 0)
+ return null;
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ return this._buildPayload(window);
+ }
+ reset() {
+ this._generation++;
+ this._retryAfter.reset();
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._flushTimer.clear();
+ this._series = new Map;
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ }
+ _capture(sample) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return;
+ const filtered = this._runBeforeSend(sample);
+ if (filtered === null)
+ return;
+ if (!filtered.name || typeof filtered.name != "string")
+ return void this._logger.warn("Dropping metric with empty name");
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
+ if (filtered.type === "count" && filtered.value < 0)
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
+ let attributes;
+ let key;
+ try {
+ attributes = filtered.attributes ? {
+ ...filtered.attributes
+ } : undefined;
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
+ } catch (e) {
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
+ return;
+ }
+ let state = this._series.get(key);
+ if (!state) {
+ if (!this._admitNewSeries())
+ return;
+ state = {
+ name: filtered.name,
+ type: filtered.type,
+ unit: filtered.unit,
+ attributes,
+ windowStartMs: Date.now()
+ };
+ this._series.set(key, state);
+ }
+ const seenType = this._typeByName.get(filtered.name);
+ if (seenType === undefined)
+ this._typeByName.set(filtered.name, filtered.type);
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
+ this._typeCollisionWarned.add(filtered.name);
+ this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
+ }
+ this._fold(state, filtered.value);
+ this._armFlushTimer();
+ }
+ _admitNewSeries() {
+ if (this._series.size < this._config.maxSeriesPerFlush)
+ return true;
+ if (!this._seriesCapWarned) {
+ this._seriesCapWarned = true;
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
+ }
+ return false;
+ }
+ _fold(state, value) {
+ switch (state.type) {
+ case "count":
+ state.total = (state.total ?? 0) + value;
+ break;
+ case "gauge":
+ state.last = value;
+ break;
+ case "histogram": {
+ if (!state.hist)
+ state.hist = {
+ count: 0,
+ sum: 0,
+ min: value,
+ max: value,
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
+ };
+ const hist = state.hist;
+ hist.count += 1;
+ hist.sum += value;
+ hist.min = Math.min(hist.min, value);
+ hist.max = Math.max(hist.max, value);
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
+ break;
+ }
+ }
+ }
+ _runBeforeSend(sample) {
+ const beforeSend = this._config.beforeSend;
+ if (!beforeSend)
+ return sample;
+ const fns = isArray(beforeSend) ? beforeSend : [
+ beforeSend
+ ];
+ let result = sample;
+ for (const fn of fns)
+ try {
+ const next = fn(result);
+ if (!next) {
+ this._logger.info("Metric was rejected in beforeSend function");
+ return null;
+ }
+ result = next;
+ } catch (e) {
+ this._logger.error("Error in beforeSend function for metric:", e);
+ return null;
+ }
+ return result;
+ }
+ _armFlushTimer() {
+ if (this._flushTimer.pending)
+ return;
+ this._flushTimer.arm(this._nextFlushDelay());
+ }
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
+ }
+ async _doFlush() {
+ this._flushTimer.clear();
+ if (this._series.size === 0)
+ return;
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ const generation = this._generation;
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
+ if (generation !== this._generation)
+ return;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ } else {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ }
+ if (this._flushTimer.pending)
+ this._flushTimer.arm(this._nextFlushDelay());
+ switch (outcome.kind) {
+ case "ok":
+ return;
+ case "retry-later":
+ this._mergeWindowBack(window);
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ return;
+ case "too-large":
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
+ return;
+ case "fatal":
+ this._logger.error("Failed to send metrics batch:", outcome.error);
+ return;
+ }
+ }
+ _buildPayload(window) {
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
+ }
+ _buildMetrics(window) {
+ const nowNano = msToUnixNano(Date.now());
+ const byMetric = new Map;
+ for (const state of window.values()) {
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
+ let metric = byMetric.get(metricKey);
+ if (!metric) {
+ metric = {
+ name: state.name,
+ ...state.unit && {
+ unit: state.unit
+ }
+ };
+ if (state.type === "count")
+ metric.sum = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ isMonotonic: true,
+ dataPoints: []
+ };
+ else if (state.type === "gauge")
+ metric.gauge = {
+ dataPoints: []
+ };
+ else
+ metric.histogram = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ dataPoints: []
+ };
+ byMetric.set(metricKey, metric);
+ }
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
+ const startNano = msToUnixNano(state.windowStartMs);
+ if (state.type === "count") {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ asDouble: state.total ?? 0
+ };
+ metric.sum.dataPoints.push(dp);
+ } else if (state.type === "gauge") {
+ const dp = {
+ attributes,
+ timeUnixNano: nowNano,
+ asDouble: state.last ?? 0
+ };
+ metric.gauge.dataPoints.push(dp);
+ } else if (state.hist) {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ count: state.hist.count,
+ sum: state.hist.sum,
+ min: state.hist.min,
+ max: state.hist.max,
+ bucketCounts: state.hist.bucketCounts,
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
+ };
+ metric.histogram.dataPoints.push(dp);
+ }
+ }
+ return Array.from(byMetric.values());
+ }
+ _mergeWindowBack(window) {
+ for (const [key, old] of window) {
+ const current = this._series.get(key);
+ if (!current) {
+ if (this._admitNewSeries())
+ this._series.set(key, old);
+ continue;
+ }
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
+ switch (current.type) {
+ case "count":
+ current.total = (current.total ?? 0) + (old.total ?? 0);
+ break;
+ case "gauge":
+ break;
+ case "histogram":
+ if (old.hist)
+ if (current.hist) {
+ current.hist.count += old.hist.count;
+ current.hist.sum += old.hist.sum;
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
+ } else
+ current.hist = old.hist;
+ break;
+ }
+ }
+ }
+}
+var OTLP_TEMPORALITY_DELTA = 1;
+var init_metrics = __esm(() => {
+ init_utils();
+ init_flush_timer();
+ init_retry_after();
+ init_backoff();
+ init_otlp_any_value();
+ init_metrics_utils();
+ init_config2();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/ids.mjs
+function getRandomBytes(byteLength) {
+ const bytes = new Uint8Array(byteLength);
+ const cryptoLike = globalThis.crypto;
+ if (cryptoLike && typeof cryptoLike.getRandomValues == "function")
+ try {
+ cryptoLike.getRandomValues(bytes);
+ return bytes;
+ } catch {}
+ for (let i = 0;i < byteLength; i++)
+ bytes[i] = Math.floor(256 * Math.random());
+ return bytes;
+}
+function bytesToHex(bytes) {
+ let hex = "";
+ for (let i = 0;i < bytes.length; i++)
+ hex += bytes[i].toString(16).padStart(2, "0");
+ return hex;
+}
+function randomHexId(byteLength) {
+ const hex = bytesToHex(getRandomBytes(byteLength));
+ return /[^0]/.test(hex) ? hex : hex.slice(0, -1) + "1";
+}
+function newTraceId() {
+ return randomHexId(TRACE_ID_BYTES);
+}
+function newSpanId() {
+ return randomHexId(SPAN_ID_BYTES);
+}
+function isValidHexId(value, length, invalid) {
+ return typeof value == "string" && value.length === length && value !== invalid && HEX_RE.test(value);
+}
+function isValidTraceId(value) {
+ return isValidHexId(value, TRACE_ID_HEX, INVALID_TRACE_ID);
+}
+function isValidSpanId(value) {
+ return isValidHexId(value, SPAN_ID_HEX, INVALID_SPAN_ID);
+}
+var TRACE_ID_BYTES = 16, SPAN_ID_BYTES = 8, TRACE_ID_HEX, SPAN_ID_HEX, INVALID_TRACE_ID, INVALID_SPAN_ID, HEX_RE;
+var init_ids = __esm(() => {
+ TRACE_ID_HEX = 2 * TRACE_ID_BYTES;
+ SPAN_ID_HEX = 2 * SPAN_ID_BYTES;
+ INVALID_TRACE_ID = "0".repeat(TRACE_ID_HEX);
+ INVALID_SPAN_ID = "0".repeat(SPAN_ID_HEX);
+ HEX_RE = /^[0-9a-f]+$/;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/traceparent.mjs
+function parseTraceparent(value) {
+ const fields = matchTraceparent(value);
+ return fields && {
+ traceId: fields.traceId,
+ spanId: fields.spanId,
+ flags: definedFlags(fields.flags)
+ };
+}
+function definedFlags(flags) {
+ return 1 & parseInt(flags, 16) ? TRACE_FLAGS_SAMPLED : TRACE_FLAGS_UNSAMPLED;
+}
+function matchTraceparent(value) {
+ if (typeof value != "string")
+ return;
+ const match = TRACEPARENT_RE.exec(value.trim());
+ if (!match)
+ return;
+ const [, version, traceId, spanId, flags, trailing] = match;
+ if (version === "ff")
+ return;
+ if (version === "00" && trailing)
+ return;
+ if (!isValidTraceId(traceId) || !isValidSpanId(spanId))
+ return;
+ return {
+ version,
+ traceId,
+ spanId,
+ flags
+ };
+}
+function normalizeTraceparent(value) {
+ return matchTraceparent(value) && value.trim();
+}
+function traceparentHeader(value) {
+ return Array.isArray(value) && value.length === 1 ? value[0] : value;
+}
+function formatTraceparent(traceId, spanId, flags = TRACE_FLAGS_SAMPLED) {
+ return `00-${traceId}-${spanId}-${flags}`;
+}
+function sanitizeTracestate(value) {
+ if (typeof value != "string")
+ return;
+ const trimmed = value.trim();
+ if (!trimmed)
+ return;
+ if (/[^\x20-\x7e\t]/.test(trimmed))
+ return;
+ const members = trimmed.split(",");
+ if (members.length > TRACESTATE_MAX_MEMBERS)
+ return;
+ for (const member of members)
+ if (member.trim() && !member.includes("="))
+ return;
+ if (trimmed.length <= TRACESTATE_MAX_LENGTH)
+ return trimmed;
+ return trimToLength(members);
+}
+function trimToLength(members) {
+ const kept = [
+ ...members
+ ];
+ const joinedLength = () => kept.reduce((total, member) => total + member.length, 0) + kept.length - 1;
+ for (let index = kept.length - 1;index >= 0 && joinedLength() > TRACESTATE_MAX_LENGTH; index--)
+ if (kept[index].length > TRACESTATE_LARGE_MEMBER_LENGTH)
+ kept.splice(index, 1);
+ while (kept.length && joinedLength() > TRACESTATE_MAX_LENGTH)
+ kept.pop();
+ return kept.length ? kept.join(",") : undefined;
+}
+var TRACEPARENT_RE, TRACE_FLAGS_SAMPLED = "01", TRACE_FLAGS_UNSAMPLED = "00", TRACESTATE_MAX_MEMBERS = 32, TRACESTATE_MAX_LENGTH = 512, TRACESTATE_LARGE_MEMBER_LENGTH = 128;
+var init_traceparent = __esm(() => {
+ init_ids();
+ TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/sanitize.mjs
+function sanitizeName(name, label, maxLength, logger) {
+ if (typeof name == "string" && name.trim())
+ return name.length > maxLength ? name.slice(0, maxLength) : name;
+ logger?.debug(`${label} must be a non-empty string; using "${FALLBACK_SPAN_NAME}"`);
+ return FALLBACK_SPAN_NAME;
+}
+function toEpochMs(value) {
+ if (value == null)
+ return;
+ let ms = value;
+ if (value instanceof Date)
+ try {
+ ms = value.getTime();
+ } catch {
+ return;
+ }
+ if (typeof ms != "number" || !Number.isFinite(ms))
+ return;
+ if (ms < MIN_TIMESTAMP_MS || ms > MAX_TIMESTAMP_MS)
+ return;
+ return ms;
+}
+function resolveStartTime(value, now, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug("Span startTime is out of range or not a valid time; using the current time");
+ return now;
+ }
+ if (now - supplied > DEEP_BACKDATE_WARNING_MS)
+ logger?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp");
+ else if (supplied > now)
+ logger?.debug("Span startTime is in the future; the span may export with a zero duration");
+ return supplied;
+}
+function clampEndTime(endTime, startTime) {
+ return endTime < startTime ? startTime : endTime;
+}
+function resolveSuppliedTime(value, derived, label, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug(`Span ${label} is out of range or not a valid time; using the derived time`);
+ return derived;
+ }
+ return supplied;
+}
+var FALLBACK_SPAN_NAME = "unknown", MAX_TIMESTAMP_MS = 9223372036854, MIN_TIMESTAMP_MS = 0, DEEP_BACKDATE_WARNING_MS = 86400000;
+var init_sanitize = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/span.mjs
+function monotonicNow() {
+ const perf = globalThis.performance;
+ return typeof perf?.now == "function" ? perf.now() : undefined;
+}
+
+class PostHogSpan {
+ constructor(init, _onEnd, _logger) {
+ this._onEnd = _onEnd;
+ this._logger = _logger;
+ this._events = [];
+ this._ended = false;
+ this._userAttributeCount = 0;
+ this._userEventCount = 0;
+ this._droppedAttributes = 0;
+ this._droppedEvents = 0;
+ this._traceId = init.traceId;
+ this._spanId = init.spanId;
+ this._parentSpanId = init.parentSpanId;
+ this._traceState = init.traceState;
+ this._traceFlags = init.traceFlags ?? TRACE_FLAGS_SAMPLED;
+ this._parentIsRemote = init.parentIsRemote ?? false;
+ this._name = init.name;
+ this._kind = init.kind;
+ this._autoKeys = new Set(init.autoAttributeKeys);
+ this._maxAttributes = init.maxAttributes;
+ this._maxEvents = init.maxEvents;
+ this._maxAttributesPerEvent = init.maxAttributesPerEvent;
+ this._maxAttributeValueLength = init.maxAttributeValueLength;
+ this._attributes = Object.create(null);
+ for (const key of Object.keys(init.attributes))
+ this._writeAttribute(key, init.attributes[key]);
+ this._startMono = init.backdated ? undefined : monotonicNow();
+ this._startTime = init.clockAnchor && this._startMono !== undefined ? init.clockAnchor.wall + (this._startMono - init.clockAnchor.mono) : init.startTime;
+ if (this._startMono !== undefined)
+ this._clockAnchor = init.clockAnchor ?? {
+ wall: this._startTime,
+ mono: this._startMono
+ };
+ }
+ _now() {
+ if (this._startMono !== undefined) {
+ const mono = monotonicNow();
+ if (mono !== undefined)
+ return this._startTime + Math.max(0, mono - this._startMono);
+ }
+ return Date.now();
+ }
+ _mutable(operation) {
+ if (this._ended) {
+ this._logger?.debug(`Ignoring ${operation} on a span that has already ended`);
+ return false;
+ }
+ return true;
+ }
+ _writeAttribute(key, value) {
+ if (isNullish(value)) {
+ if (key in this._attributes && !this._autoKeys.has(key))
+ this._userAttributeCount--;
+ delete this._attributes[key];
+ return;
+ }
+ if (!this._autoKeys.has(key) && !(key in this._attributes)) {
+ if (this._userAttributeCount >= this._maxAttributes)
+ return void this._droppedAttributes++;
+ this._userAttributeCount++;
+ }
+ this._attributes[key] = truncateAttributeValue(value, this._maxAttributeValueLength);
+ }
+ setAttribute(key, value) {
+ if (this._mutable("setAttribute"))
+ this._writeAttribute(key, value);
+ return this;
+ }
+ setAttributes(attributes) {
+ if (this._mutable("setAttributes")) {
+ const safe = assignUserAttributes({}, attributes);
+ for (const key of Object.keys(safe))
+ this._writeAttribute(key, safe[key]);
+ }
+ return this;
+ }
+ addEvent(name, attributes, timestamp) {
+ if (this._mutable("addEvent")) {
+ if (this._userEventCount >= this._maxEvents) {
+ this._droppedEvents++;
+ return this;
+ }
+ this._userEventCount++;
+ const bounded = attributes && boundAttributes(attributes, this._maxAttributesPerEvent, this._maxAttributeValueLength);
+ this._events.push({
+ name: sanitizeName(name, "Span event name", this._maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(timestamp, this._now(), "event timestamp", this._logger),
+ ...bounded && {
+ attributes: bounded.attributes,
+ ...bounded.dropped && {
+ droppedAttributesCount: bounded.dropped
+ }
+ }
+ });
+ }
+ return this;
+ }
+ setStatus(status, message) {
+ if (this._mutable("setStatus")) {
+ if (status !== "ok" && status !== "error") {
+ this._logger?.debug(`Ignoring unknown span status "${String(status)}"; expected "ok" or "error"`);
+ return this;
+ }
+ this._status = {
+ code: status,
+ ...message && {
+ message: truncateString(message, this._maxAttributeValueLength)
+ }
+ };
+ }
+ return this;
+ }
+ get statusIsExplicitlyOk() {
+ return this._status?.code === "ok";
+ }
+ recordException(error) {
+ if (!this._mutable("recordException"))
+ return this;
+ const { type, message, stack } = describeError(error);
+ this.addEvent(EXCEPTION_EVENT_NAME, {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
+ }
+ });
+ return this.setStatus("error", message);
+ }
+ updateName(name) {
+ if (this._mutable("updateName"))
+ this._name = sanitizeName(name, "Span name", this._maxAttributeValueLength, this._logger);
+ return this;
+ }
+ traceparent() {
+ return formatTraceparent(this._traceId, this._spanId, this._traceFlags);
+ }
+ tracestate() {
+ return this._traceState ?? null;
+ }
+ childContext() {
+ return {
+ traceId: this._traceId,
+ parentSpanId: this._spanId,
+ traceState: this._traceState,
+ traceFlags: this._traceFlags,
+ clockAnchor: this._clockAnchor
+ };
+ }
+ end(endTime) {
+ if (this._ended)
+ return void this._logger?.debug("Ignoring end() on a span that has already ended");
+ this._ended = true;
+ const derived = this._now();
+ const resolved = resolveSuppliedTime(endTime, derived, "end time", this._logger);
+ this._onEnd({
+ traceId: this._traceId,
+ spanId: this._spanId,
+ ...this._parentSpanId && {
+ parentSpanId: this._parentSpanId
+ },
+ ...this._traceState && {
+ traceState: this._traceState
+ },
+ traceFlags: this._traceFlags,
+ parentIsRemote: this._parentIsRemote,
+ name: this._name,
+ kind: this._kind,
+ ...this._status && {
+ status: this._status
+ },
+ attributes: {
+ ...this._attributes
+ },
+ events: this._events,
+ startTime: this._startTime,
+ endTime: clampEndTime(resolved, this._startTime),
+ ...this._droppedAttributes && {
+ droppedAttributesCount: this._droppedAttributes
+ },
+ ...this._droppedEvents && {
+ droppedEventsCount: this._droppedEvents
+ }
+ }, this._autoKeys);
+ }
+}
+function safeString(value) {
+ try {
+ return typeof value == "string" ? value : String(value);
+ } catch {
+ return UNSERIALIZABLE_VALUE;
+ }
+}
+function nonNegativeCount(value) {
+ if (typeof value != "number" || !Number.isFinite(value) || value <= 0)
+ return 0;
+ return Math.min(Math.floor(value), MAX_UINT32);
+}
+function orderedKeys(attributes, keysBeforeHook) {
+ if (!keysBeforeHook.length)
+ return Object.keys(attributes);
+ const beforeHook = keysBeforeHook.filter((key) => Object.prototype.propertyIsEnumerable.call(attributes, key));
+ const seen = new Set(beforeHook);
+ return [
+ ...beforeHook,
+ ...Object.keys(attributes).filter((key) => !seen.has(key))
+ ];
+}
+function applySpanLimits(record, autoKeys, maxAttributes, maxEvents, maxAttributesPerEvent, maxAttributeValueLength, keysBeforeHook = []) {
+ let kept = 0;
+ let droppedAttributes = 0;
+ const attributes = {};
+ for (const key of orderedKeys(record.attributes, keysBeforeHook)) {
+ const value = record.attributes[key];
+ if (!isNullish(value)) {
+ if (!autoKeys.has(key)) {
+ if (kept >= maxAttributes) {
+ droppedAttributes++;
+ continue;
+ }
+ kept++;
+ }
+ Object.defineProperty(attributes, key, {
+ value: truncateAttributeValue(value, maxAttributeValueLength),
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ }
+ record.attributes = attributes;
+ if (droppedAttributes)
+ record.droppedAttributesCount = nonNegativeCount(record.droppedAttributesCount) + droppedAttributes;
+ let keptEvents = 0;
+ let droppedEvents = 0;
+ const events = [];
+ for (const event of record.events) {
+ if (keptEvents >= maxEvents) {
+ droppedEvents++;
+ continue;
+ }
+ keptEvents++;
+ if (event.attributes) {
+ const bounded = boundAttributes(event.attributes, maxAttributesPerEvent, maxAttributeValueLength);
+ event.attributes = bounded.attributes;
+ if (bounded.dropped)
+ event.droppedAttributesCount = nonNegativeCount(event.droppedAttributesCount) + bounded.dropped;
+ }
+ events.push(event);
+ }
+ record.events = events;
+ if (droppedEvents)
+ record.droppedEventsCount = nonNegativeCount(record.droppedEventsCount) + droppedEvents;
+ if (record.status?.message)
+ record.status = {
+ ...record.status,
+ message: truncateString(safeString(record.status.message), maxAttributeValueLength)
+ };
+}
+
+class NoopSpan {
+ setAttribute() {
+ return this;
+ }
+ setAttributes() {
+ return this;
+ }
+ addEvent() {
+ return this;
+ }
+ setStatus() {
+ return this;
+ }
+ recordException() {
+ return this;
+ }
+ updateName() {
+ return this;
+ }
+ traceparent() {
+ return null;
+ }
+ tracestate() {
+ return null;
+ }
+ end() {}
+}
+function readStack(error) {
+ try {
+ const stack = error.stack;
+ return typeof stack == "string" && stack ? {
+ stack
+ } : {};
+ } catch {
+ return {};
+ }
+}
+function inertSpan(options, active) {
+ const parent = traceparentHeader(options?.parent) ?? active;
+ const inbound = typeof parent == "string" || parent == null ? parent : readHandle(parent, "traceparent");
+ const traceparent = normalizeTraceparent(inbound);
+ if (!traceparent)
+ return NOOP_SPAN;
+ const tracestate = typeof parent == "string" || parent == null ? options?.tracestate : readHandle(parent, "tracestate");
+ return new PassThroughSpan(traceparent, sanitizeTracestate(tracestate));
+}
+function readHandle(parent, method) {
+ try {
+ const fn = parent[method];
+ return typeof fn == "function" ? fn.call(parent) : undefined;
+ } catch {
+ return;
+ }
+}
+function truncateString(value, maxLength) {
+ return value.length > maxLength ? value.slice(0, maxLength) : value;
+}
+function truncateAttributeValue(value, maxLength) {
+ return truncateValue(value, maxLength, {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ }, 0);
+}
+function truncateValue(value, maxLength, state, depth) {
+ if (value === null || typeof value != "object") {
+ if (isNullish(value))
+ return value;
+ if (state.remainingNodes <= 0)
+ return value;
+ state.remainingNodes--;
+ return typeof value == "string" ? truncateString(value, maxLength) : value;
+ }
+ if (state.ancestors.has(value))
+ return CIRCULAR_VALUE;
+ if (state.remainingNodes <= 0 || depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return value;
+ state.remainingNodes--;
+ state.ancestors.add(value);
+ try {
+ if (value instanceof Date)
+ return value;
+ const resolved = resolveToJson(value);
+ if (resolved.selfDescribed)
+ return isNullish(resolved.value) ? String(resolved.value) : truncateValue(resolved.value, maxLength, state, depth + 1);
+ if (isArray(value)) {
+ const walked = Math.min(value.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ const boundedItems = [];
+ for (let index = 0;index < walked; index++)
+ try {
+ boundedItems.push(truncateValue(value[index], maxLength, state, depth + 1));
+ } catch {
+ boundedItems.push(UNSERIALIZABLE_VALUE);
+ }
+ if (value.length > walked)
+ boundedItems.length = value.length;
+ return boundedItems;
+ }
+ const bounded = {};
+ let emittable = 0;
+ for (const key of Object.keys(value)) {
+ if (emittable >= MAX_JSON_SAFE_VALUE_ITEMS)
+ break;
+ let boundedItem;
+ try {
+ boundedItem = truncateValue(value[key], maxLength, state, depth + 1);
+ } catch {
+ boundedItem = UNSERIALIZABLE_VALUE;
+ }
+ if (key && !isNullish(boundedItem))
+ emittable++;
+ Object.defineProperty(bounded, key, {
+ value: boundedItem,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ return bounded;
+ } catch {
+ return value;
+ } finally {
+ state.ancestors.delete(value);
+ }
+}
+function resolveToJson(value) {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
return {
- kind: "fatal",
- error: new Error("The client is disabled")
+ selfDescribed: true,
+ value: toJSON.call(value)
};
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
+ } catch {}
+ return {
+ selfDescribed: false
+ };
+}
+function boundAttributes(source, max, maxLength) {
+ let keys;
+ try {
+ keys = Object.keys(source);
+ } catch {
+ return {
+ attributes: {},
+ dropped: 0
};
+ }
+ const attributes = {};
+ let kept = 0;
+ let dropped = 0;
+ for (const key of keys) {
+ if (kept >= max) {
+ dropped++;
+ continue;
+ }
+ let value;
try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
- }
+ value = truncateAttributeValue(source[key], maxLength);
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ if (!isNullish(value)) {
+ kept++;
+ Object.defineProperty(attributes, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
});
- return {
- kind: "ok"
- };
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (err instanceof PostHogFetchNetworkError)
- return {
- kind: "retry-later",
- error: err
- };
- return {
- kind: "fatal",
- error: err
- };
}
}
- async _sendMetricsBatch(payload) {
- if (this.disabled)
+ return {
+ attributes,
+ dropped
+ };
+}
+function truncateAttributes(attributes, maxLength) {
+ for (const key of Object.keys(attributes))
+ attributes[key] = truncateAttributeValue(attributes[key], maxLength);
+ return attributes;
+}
+function runWithActiveSpan(contextManager, span, fn) {
+ return span === NOOP_SPAN ? fn(span) : contextManager.with(span, () => fn(span));
+}
+function describeError(error) {
+ try {
+ const stack = readStack(error);
+ if (isError(error))
return {
- kind: "fatal",
- error: new Error("The client is disabled")
+ type: error.name || "Error",
+ message: error.message || "",
+ ...stack
};
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
- };
- try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
- }
- });
+ if (typeof error == "string")
return {
- kind: "ok"
+ type: "string",
+ message: error
};
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (isPostHogFetchRetryableError(err))
+ if (error && typeof error == "object") {
+ const maybe = error;
+ if (typeof maybe.message == "string")
return {
- kind: "retry-later",
- error: err
+ type: typeof maybe.name == "string" ? maybe.name : "Object",
+ message: maybe.message,
+ ...stack
};
- return {
- kind: "fatal",
- error: err
+ }
+ return {
+ type: typeof error,
+ message: String(error)
+ };
+ } catch {
+ return {
+ type: typeof error,
+ message: ""
+ };
+ }
+}
+var EXCEPTION_EVENT_NAME = "exception", MAX_UINT32 = 4294967295, NOOP_SPAN, PassThroughSpan;
+var init_span = __esm(() => {
+ init_traceparent();
+ init_sanitize();
+ init_utils();
+ init_json_utils();
+ NOOP_SPAN = /* @__PURE__ */ new NoopSpan;
+ PassThroughSpan = class PassThroughSpan extends NoopSpan {
+ constructor(_traceparent, _tracestate) {
+ super(), this._traceparent = _traceparent, this._tracestate = _tracestate;
+ }
+ traceparent() {
+ return this._traceparent;
+ }
+ tracestate() {
+ return this._tracestate ?? null;
+ }
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/otlp.mjs
+function spanFlags(record) {
+ const traceFlags = parseInt(record.traceFlags, 16);
+ const w3c = Number.isFinite(traceFlags) ? 255 & traceFlags : TRACE_FLAGS_SAMPLED2;
+ return w3c | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE | (record.parentIsRemote ? SPAN_FLAGS_CONTEXT_IS_REMOTE : 0);
+}
+function wireString(value) {
+ if (typeof value == "string")
+ return sanitizeString(value);
+ try {
+ return sanitizeString(String(value));
+ } catch {
+ return UNSERIALIZABLE_VALUE;
+ }
+}
+function spanKindToOtlp(kind) {
+ if (kind && Object.prototype.hasOwnProperty.call(SPAN_KIND_TO_OTLP, kind))
+ return SPAN_KIND_TO_OTLP[kind];
+ return SPAN_KIND_TO_OTLP.internal;
+}
+function msToUnixNanoString(ms) {
+ let whole = Math.floor(ms);
+ let fractionalNanos = Math.round((ms - whole) * 1e6);
+ if (fractionalNanos >= 1e6) {
+ whole += 1;
+ fractionalNanos = 0;
+ }
+ return String(whole) + String(fractionalNanos).padStart(6, "0");
+}
+function toOtlpEvent(event, logger) {
+ const encoded = {
+ name: wireString(event.name),
+ timeUnixNano: msToUnixNanoString(event.timestamp)
+ };
+ if (event.attributes) {
+ const attributes = toOtlpKeyValueList(event.attributes, logger);
+ if (attributes.length)
+ encoded.attributes = attributes;
+ }
+ const dropped = nonNegativeCount(event.droppedAttributesCount);
+ if (dropped)
+ encoded.droppedAttributesCount = dropped;
+ return encoded;
+}
+function buildOtlpSpan(record, logger) {
+ const span = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ name: wireString(record.name),
+ kind: spanKindToOtlp(record.kind),
+ startTimeUnixNano: msToUnixNanoString(record.startTime),
+ endTimeUnixNano: msToUnixNanoString(record.endTime),
+ flags: spanFlags(record)
+ };
+ if (record.parentSpanId)
+ span.parentSpanId = record.parentSpanId;
+ if (record.traceState)
+ span.traceState = wireString(record.traceState);
+ const attributes = toOtlpKeyValueList(record.attributes, logger);
+ if (attributes.length)
+ span.attributes = attributes;
+ if (record.events.length)
+ span.events = record.events.map((event) => toOtlpEvent(event, logger));
+ const droppedAttributes = nonNegativeCount(record.droppedAttributesCount);
+ if (droppedAttributes)
+ span.droppedAttributesCount = droppedAttributes;
+ const droppedEvents = nonNegativeCount(record.droppedEventsCount);
+ if (droppedEvents)
+ span.droppedEventsCount = droppedEvents;
+ if (record.status)
+ span.status = {
+ code: SPAN_STATUS_TO_OTLP[record.status.code],
+ ...record.status.message && {
+ message: wireString(record.status.message)
+ }
+ };
+ return span;
+}
+function buildTracesResourceAttributes(config, sdkName, sdkVersion) {
+ return buildOtlpResourceAttributes(config, sdkName, sdkVersion);
+}
+function buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, logger) {
+ return {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes, logger)
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ spans
+ }
+ ]
+ }
+ ]
+ };
+}
+var SPAN_KIND_TO_OTLP, SPAN_STATUS_TO_OTLP, TRACE_FLAGS_SAMPLED2 = 1, SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE = 256, SPAN_FLAGS_CONTEXT_IS_REMOTE = 512;
+var init_otlp = __esm(() => {
+ init_span();
+ init_otlp_any_value();
+ init_json_utils();
+ init_otlp_resource();
+ SPAN_KIND_TO_OTLP = {
+ internal: 1,
+ server: 2,
+ client: 3,
+ producer: 4,
+ consumer: 5
+ };
+ SPAN_STATUS_TO_OTLP = {
+ ok: 1,
+ error: 2
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/index.mjs
+function clockNow() {
+ return monotonicNow() ?? Date.now();
+}
+function isOwnSpan(value) {
+ try {
+ return value instanceof PostHogSpan;
+ } catch {
+ return false;
+ }
+}
+function remoteContext(header, tracestate) {
+ const remote = parseTraceparent(header);
+ if (!remote)
+ return;
+ return {
+ traceId: remote.traceId,
+ parentSpanId: remote.spanId,
+ traceState: sanitizeTracestate(tracestate),
+ traceFlags: remote.flags,
+ isRemote: true
+ };
+}
+function looksLikeSpan(value) {
+ try {
+ return typeof value.traceparent == "function";
+ } catch {
+ return false;
+ }
+}
+function isSpanRecordShape(record) {
+ return !!record.attributes && typeof record.attributes == "object" && !Array.isArray(record.attributes) && Array.isArray(record.events) && record.name !== undefined && record.kind !== undefined && record.startTime !== undefined && record.endTime !== undefined;
+}
+function restoreField(record, field, value) {
+ if (record[field] !== value)
+ record[field] = value;
+}
+function withRestoredIdentity(hooked, original) {
+ try {
+ const descriptors = Object.getOwnPropertyDescriptors(hooked);
+ for (const field of [
+ "traceId",
+ "spanId",
+ "parentSpanId",
+ "traceState"
+ ])
+ descriptors[field] = {
+ value: original[field],
+ enumerable: true,
+ writable: true,
+ configurable: true
};
+ return Object.create(Object.getPrototypeOf(hooked), descriptors);
+ } catch {
+ return hooked;
+ }
+}
+
+class PostHogTraces {
+ constructor(_instance, _config, _logger, _getContext, _contextManager, _onSpanQueued) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._getContext = _getContext;
+ this._contextManager = _contextManager;
+ this._onSpanQueued = _onSpanQueued;
+ this._queue = [];
+ this._flushTimer = new FlushTimer(() => this._flushInBackground());
+ this._flushPromise = null;
+ this._droppedSinceWarning = 0;
+ this._lastDropWarningAt = 0;
+ this._dropReasons = new Set;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter = new RetryAfterWindow;
+ this._headBatchFailures = 0;
+ this._headBatchSize = 0;
+ this._headBatchChargeableAt = 0;
+ this._generation = 0;
+ this._liveSpans = new Map;
+ this._maxExportBatchSize = _config.maxExportBatchSize;
+ }
+ startSpan(name, options) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return inertSpan(options, this._contextManager.active());
+ const explicitParent = traceparentHeader(options?.parent);
+ if (explicitParent && typeof explicitParent != "string" && !isOwnSpan(explicitParent)) {
+ if (looksLikeSpan(explicitParent)) {
+ this._logger.debug("Span parent is not a span from this SDK; returning an inert span");
+ return inertSpan(options, this._contextManager.active());
+ }
+ this._logger.debug("Ignoring an unusable span parent");
+ }
+ const parent = this._resolveParent(explicitParent, options);
+ this._evictAgedSpans();
+ if (this._liveSpans.size >= this._config.maxLiveSpans) {
+ this._recordDrop(1, `the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`);
+ return inertSpan(options, this._contextManager.active());
+ }
+ const now = Date.now();
+ const startTime = resolveStartTime(options?.startTime, now, this._logger);
+ const spanId = newSpanId();
+ this._liveSpans.set(spanId, clockNow());
+ const autoAttributes = this._autoContextAttributes();
+ return new PostHogSpan({
+ traceId: parent?.traceId ?? newTraceId(),
+ spanId,
+ parentSpanId: parent?.parentSpanId,
+ traceState: parent?.traceState,
+ traceFlags: parent?.traceFlags,
+ parentIsRemote: parent?.isRemote,
+ name: sanitizeName(name, "Span name", this._config.maxAttributeValueLength, this._logger),
+ kind: options?.kind ?? "internal",
+ attributes: assignUserAttributes({
+ ...autoAttributes
+ }, options?.attributes),
+ autoAttributeKeys: Object.keys(autoAttributes),
+ maxAttributes: this._config.maxAttributesPerSpan,
+ maxEvents: this._config.maxEventsPerSpan,
+ maxAttributesPerEvent: this._config.maxAttributesPerEvent,
+ maxAttributeValueLength: this._config.maxAttributeValueLength,
+ startTime,
+ backdated: startTime !== now,
+ clockAnchor: toEpochMs(options?.startTime) === undefined ? parent?.clockAnchor : undefined
+ }, (record, autoKeys) => this._onSpanEnd(record, autoKeys), this._logger);
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const span = this.startSpan(name, options);
+ try {
+ const result = runWithActiveSpan(this._contextManager, span, fn);
+ if (isPromise(result))
+ return result.then((value) => {
+ span.end();
+ return value;
+ }, (error) => {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
+ });
+ span.end();
+ return result;
+ } catch (error) {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
}
}
- async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
- const body = options.body ? options.body : "";
- let reqByteLength = -1;
+ getActiveSpan() {
+ return this._contextManager.active() ?? null;
+ }
+ get throttled() {
+ return this._retryAfter.isOpen();
+ }
+ async flush() {
+ for (;; ) {
+ if (!this._queue.length)
+ return;
+ const inFlight = this._flushPromise;
+ const removed = await (inFlight ?? this._startFlush());
+ if (!removed)
+ return;
+ }
+ }
+ _startFlush() {
+ this._flushTimer.clear();
+ const startedAtGeneration = this._generation;
+ const promise = Promise.resolve().then(() => startedAtGeneration === this._generation ? this._flushInner() : 0).finally(() => {
+ if (this._flushPromise === promise)
+ this._flushPromise = null;
+ this._armFlushTimerIfQueuedNoEarlierThan();
+ });
+ this._flushPromise = promise;
+ return promise;
+ }
+ reset() {
+ this._flushTimer.clear();
+ if (this._queue.length)
+ this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`);
+ this._queue = [];
+ this._liveSpans.clear();
+ this._flushPromise = null;
+ this._generation++;
+ this._maxExportBatchSize = this._config.maxExportBatchSize;
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ this._lastDropWarningAt = 0;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter.reset();
+ this._resetHeadBatchBudget();
+ }
+ _resetHeadBatchBudget() {
+ this._headBatchFailures = 0;
+ this._headBatchChargeableAt = 0;
+ }
+ _resolveParent(explicit, options) {
+ if (typeof explicit == "string") {
+ const remote = remoteContext(explicit, options?.tracestate);
+ if (!remote)
+ this._logger.debug("Ignoring malformed traceparent; starting a new trace");
+ return remote;
+ }
+ if (isOwnSpan(explicit))
+ return explicit.childContext();
+ const active = this._contextManager.active();
+ if (isOwnSpan(active))
+ return active.childContext();
+ if (active instanceof PassThroughSpan)
+ return remoteContext(active.traceparent(), active.tracestate() ?? undefined);
+ }
+ _autoContextAttributes() {
+ let context;
try {
- reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
- } catch {
- if (body instanceof Blob)
- reqByteLength = body.size;
- else if (body instanceof Uint8Array)
- reqByteLength = body.byteLength;
- else {
- const encoded = new TextEncoder().encode(body);
- reqByteLength = encoded.length;
+ context = this._getContext();
+ } catch (error) {
+ this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes", error);
+ return {};
+ }
+ const attributes = {};
+ if (context.distinctId)
+ attributes.posthogDistinctId = context.distinctId;
+ if (context.sessionId)
+ attributes.sessionId = context.sessionId;
+ if (context.currentUrl)
+ attributes["url.full"] = context.currentUrl;
+ if (context.screenName)
+ attributes["screen.name"] = context.screenName;
+ if (context.appState)
+ attributes["app.state"] = context.appState;
+ return attributes;
+ }
+ _recordCallbackError(span, error) {
+ if (!(span instanceof PostHogSpan))
+ return;
+ const { type, message, stack } = describeError(error);
+ span.addEvent("exception", {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
}
+ });
+ if (!span.statusIsExplicitlyOk)
+ span.setStatus("error", message);
+ }
+ _evictAgedSpans() {
+ const cutoff = clockNow() - this._config.maxSpanAgeMs;
+ let evicted = 0;
+ for (const [spanId, startedAt] of this._liveSpans) {
+ if (startedAt > cutoff)
+ break;
+ this._liveSpans.delete(spanId);
+ evicted++;
}
- const retriableOptions = {
- ...this._retryOptions,
- ...retryOptions
+ if (evicted)
+ this._recordDrop(evicted, `they were still live after ${this._config.maxSpanAgeMs}ms`);
+ }
+ _onSpanEnd(incoming, autoKeys) {
+ if (!this._liveSpans.delete(incoming.spanId))
+ return;
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return void this._recordDrop(1, "the user has opted out");
+ const record = this._runBeforeSpanSend(incoming, autoKeys);
+ if (!record)
+ return;
+ this._reportLimitDrops(record);
+ if (this._queue.length >= this._config.maxQueueSize)
+ return void this._recordDrop(1, `the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);
+ this._queue.push(record);
+ try {
+ this._onSpanQueued?.();
+ } catch (error) {
+ this._logger.debug("Span queue notification failed", error);
+ }
+ if (!(this._queue.length >= this._maxExportBatchSize) || this._consecutiveFlushFailures || this._retryAfter.isOpen())
+ this._armFlushTimerIfQueued();
+ else
+ this._flushInBackground();
+ }
+ _reportLimitDrops(record) {
+ const attributes = record.droppedAttributesCount ?? 0;
+ const events = record.droppedEventsCount ?? 0;
+ let eventAttributes = 0;
+ for (const event of record.events)
+ eventAttributes += event.droppedAttributesCount ?? 0;
+ if (attributes || events || eventAttributes)
+ this._logger.debug(`Span limits discarded data from "${record.name}": ${attributes} attributes, ${events} events, ${eventAttributes} event attributes`);
+ }
+ _runBeforeSpanSend(record, autoKeys) {
+ if (!this._config.beforeSpanSend.length)
+ return record;
+ const identity = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ parentSpanId: record.parentSpanId,
+ traceState: record.traceState
};
- let attempt = 0;
- return await retriable(async () => {
- attempt++;
- const ctrl = new AbortController;
- const timeoutMs = requestTimeout ?? this.requestTimeout;
- const requestDeadline = Date.now() + timeoutMs;
- let timer;
- const deadline = new Promise((_resolve, reject) => {
- timer = safeSetTimeout(() => {
- const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
- timeoutError.name = "AbortError";
- reject(timeoutError);
- ctrl.abort(timeoutError);
- }, timeoutMs);
- });
- let res;
- let responseAccepted = false;
- let cancellation;
- const cancelBody = () => cancellation ??= (async () => {
- try {
- await res?.body?.cancel();
- } catch {}
- })();
- try {
- let fetchPromise;
- try {
- fetchPromise = this.fetch(url, {
- signal: ctrl.signal,
- ...options
- });
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
- }
- fetchPromise.then((lateResponse) => {
- if (ctrl.signal.aborted && !responseAccepted)
- Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
- }).catch(() => {});
- try {
- res = await Promise.race([
- fetchPromise,
- deadline
- ]);
- responseAccepted = true;
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
- }
- const isNoCors = options.mode === "no-cors";
- if (!isNoCors && (res.status < 200 || res.status >= 400))
- throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
- if (responseHandling.type === "successful-write") {
- try {
- await Promise.race([
- cancelBody(),
- deadline
- ]);
- } catch {}
- return;
- }
- try {
- return await Promise.race([
- responseHandling.consume(res),
- deadline
- ]);
- } catch (e) {
- if (ctrl.signal.aborted)
- throw new PostHogFetchNetworkError(e);
- throw e;
+ const originalTimes = {
+ startTime: record.startTime,
+ endTime: record.endTime
+ };
+ const originalDropped = {
+ attributes: record.droppedAttributesCount,
+ events: record.droppedEventsCount
+ };
+ const keysBeforeHook = Object.keys(record.attributes);
+ const originalPropagation = {
+ traceFlags: record.traceFlags,
+ parentIsRemote: record.parentIsRemote
+ };
+ const originalStatus = record.status && {
+ ...record.status
+ };
+ let hooked = record;
+ let current = record;
+ try {
+ for (const hook of this._config.beforeSpanSend) {
+ const result = hook(hooked);
+ if (!result) {
+ this._recordDrop(1, "beforeSpanSend dropped it");
+ return null;
}
- } finally {
- clearTimeout(timer);
- if (ctrl.signal.aborted && res)
- cancelBody();
+ hooked = this._keepSpanIdentity(result, identity);
+ }
+ const rebuilt = {
+ traceId: identity.traceId,
+ spanId: identity.spanId,
+ parentSpanId: identity.parentSpanId,
+ traceState: identity.traceState,
+ name: hooked.name,
+ kind: hooked.kind,
+ status: hooked.status,
+ attributes: hooked.attributes,
+ events: hooked.events,
+ startTime: hooked.startTime,
+ endTime: hooked.endTime,
+ traceFlags: originalPropagation.traceFlags,
+ parentIsRemote: originalPropagation.parentIsRemote,
+ droppedAttributesCount: originalDropped.attributes,
+ droppedEventsCount: originalDropped.events
+ };
+ current = rebuilt;
+ if (!isSpanRecordShape(current)) {
+ this._logger.debug("beforeSpanSend did not return a span record; dropping the span");
+ this._recordDrop(1, "beforeSpanSend returned an unusable record");
+ return null;
}
- }, {
- ...retriableOptions,
- retryCheck: (error) => {
- const shouldRetry = retriableOptions.retryCheck(error);
- if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
- error.cancelResponseBody();
- return shouldRetry;
+ current.name = sanitizeName(current.name, "Span name", this._config.maxAttributeValueLength, this._logger);
+ if (current.status && current.status.code !== "ok" && current.status.code !== "error") {
+ this._logger.debug("beforeSpanSend set an unknown span status; keeping the original");
+ current.status = originalStatus;
}
- });
+ current.startTime = toEpochMs(current.startTime) ?? originalTimes.startTime;
+ current.endTime = clampEndTime(toEpochMs(current.endTime) ?? originalTimes.endTime, current.startTime);
+ const sanitizedEvents = [];
+ for (const event of current.events)
+ try {
+ sanitizedEvents.push({
+ ...event,
+ name: sanitizeName(event.name, "Span event name", this._config.maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(event.timestamp, current.startTime, "event timestamp", this._logger)
+ });
+ } catch {
+ this._logger.debug("beforeSpanSend left an unreadable span event; dropping it");
+ }
+ current.events = sanitizedEvents;
+ applySpanLimits(current, autoKeys, this._config.maxAttributesPerSpan, this._config.maxEventsPerSpan, this._config.maxAttributesPerEvent, this._config.maxAttributeValueLength, keysBeforeHook);
+ return current;
+ } catch (error) {
+ this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed", error);
+ this._recordDrop(1, "beforeSpanSend failed");
+ return null;
+ }
}
- async _shutdown(shutdownTimeoutMs = 30000) {
- await this._initPromise;
- let hasTimedOut = false;
- this.clearFlushTimer();
- if (this.disabled)
+ _keepSpanIdentity(hooked, original) {
+ if (hooked.traceId !== original.traceId || hooked.spanId !== original.spanId || hooked.parentSpanId !== original.parentSpanId)
+ this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");
+ try {
+ restoreField(hooked, "traceId", original.traceId);
+ restoreField(hooked, "spanId", original.spanId);
+ restoreField(hooked, "parentSpanId", original.parentSpanId);
+ restoreField(hooked, "traceState", original.traceState);
+ } catch {
+ return withRestoredIdentity(hooked, original);
+ }
+ return hooked;
+ }
+ _recordDrop(count, reason) {
+ this._droppedSinceWarning += count;
+ this._dropReasons.add(reason);
+ if (Date.now() - this._lastDropWarningAt >= this._config.flushIntervalMs)
+ this._warnAboutDrops();
+ }
+ _warnAboutDrops() {
+ if (!this._droppedSinceWarning)
return;
- const doShutdown = async () => {
+ this._lastDropWarningAt = Date.now();
+ this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[
+ ...this._dropReasons
+ ].join("; ")}`);
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ }
+ _encodeBatch(batch) {
+ const encoded = [];
+ for (const record of batch)
try {
- await this.promiseQueue.join();
- while (true) {
- const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
- if (!hasQueuedEvents)
- break;
- const dequeuedBeforeFlush = this._dequeuedMessagesCount;
- await this.flush();
- if (hasTimedOut)
- break;
- if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
- this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
- break;
+ encoded.push(buildOtlpSpan(record, this._logger));
+ } catch (error) {
+ this._logger.debug("Failed to encode a span; dropping it", error);
+ this._recordDrop(1, "its attributes could not be encoded");
+ }
+ return encoded;
+ }
+ _discardQueueIfConsentWithdrawn() {
+ if (!this._instance.isDisabled && !this._instance.optedOut)
+ return 0;
+ const discarded = this._queue.length;
+ this._queue = [];
+ this._resetHeadBatchBudget();
+ this._recordDrop(discarded, "the user has opted out");
+ this._warnAboutDrops();
+ return discarded;
+ }
+ async _flushInner() {
+ if (!this._queue.length)
+ return 0;
+ const discardedBeforeDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedBeforeDrain)
+ return discardedBeforeDrain;
+ const resourceAttributes = truncateAttributes(buildTracesResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._config.maxAttributeValueLength);
+ const scopeName = this._instance.getLibraryId();
+ const scopeVersion = this._instance.getLibraryVersion();
+ let remaining = this._queue.length;
+ let removed = 0;
+ let localCap = 1 / 0;
+ const generation = this._generation;
+ try {
+ while (remaining > 0 && this._queue.length > 0) {
+ const discardedMidDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedMidDrain)
+ return removed + discardedMidDrain;
+ const cap = this._headBatchFailures > 0 ? Math.min(this._maxExportBatchSize, this._headBatchSize) : this._maxExportBatchSize;
+ const size = Math.max(1, Math.min(cap, localCap, remaining, this._queue.length));
+ const batch = this._queue.slice(0, size);
+ const spans = this._encodeBatch(batch);
+ if (!spans.length) {
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._resetHeadBatchBudget();
+ continue;
+ }
+ const chargeable = clockNow() >= this._headBatchChargeableAt && !this._retryAfter.isOpen();
+ const outcome = await this._instance._sendTracesBatch(buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, this._logger));
+ if (generation !== this._generation)
+ break;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "ok") {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ if (this._maxExportBatchSize < this._config.maxExportBatchSize)
+ this._maxExportBatchSize++;
+ continue;
+ }
+ if (outcome.kind === "too-large") {
+ if (size === 1) {
+ this._queue.splice(0, 1);
+ remaining -= 1;
+ removed += 1;
+ this._recordDrop(1, "it is too large for the ingestion endpoint");
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ continue;
}
+ const halved = Math.max(1, Math.floor(size / 2));
+ if (outcome.measuredLocally)
+ localCap = halved;
+ else
+ this._maxExportBatchSize = halved;
+ this._resetHeadBatchBudget();
+ this._logger.debug(`Batch too large; retrying the same spans in batches of ${halved}`);
+ continue;
}
- } catch (e) {
- if (!isPostHogFetchError(e))
- throw e;
- await logFlushError(e);
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ this._headBatchSize = size;
+ if (chargeable) {
+ this._headBatchFailures++;
+ this._headBatchChargeableAt = clockNow() + this._nextFlushDelay();
+ }
+ if (this._headBatchFailures < MAX_RETRIES_PER_BATCH) {
+ this._logger.debug("Span export failed; retrying on the next flush", outcome.error);
+ return removed;
+ }
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, `the ingestion endpoint failed ${MAX_RETRIES_PER_BATCH} times in a row`);
+ if (this._retryAfter.isOpen())
+ return removed;
+ continue;
+ }
+ this._logger.debug("Dropping a span batch the ingestion endpoint rejected", outcome.error);
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, "the ingestion endpoint rejected the batch");
}
- };
- return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
- this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
- shutdownTimeoutMs
- });
- hasTimedOut = true;
+ return removed;
+ } finally {
+ this._warnAboutDrops();
+ }
+ }
+ _flushInBackground() {
+ if (this._backgroundFlush)
+ return;
+ this._backgroundFlush = this.flush().catch((error) => {
+ this._logger.debug("Background span flush failed", error);
+ }).finally(() => {
+ this._backgroundFlush = undefined;
+ this._armFlushTimerIfQueuedNoEarlierThan();
});
}
- async shutdown(shutdownTimeoutMs = 30000) {
- if (this.shutdownPromise)
- this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
- else
- this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
- this.shutdownPromise = null;
- });
- return this.shutdownPromise;
+ _armFlushTimerIfQueued() {
+ if (this._flushTimer.pending || !this._queue.length)
+ return;
+ this._flushTimer.arm(this._nextFlushDelay());
+ }
+ _armFlushTimerIfQueuedNoEarlierThan() {
+ if (!this._queue.length)
+ return;
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ }
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
}
}
-var PostHogFetchHttpError, PostHogFetchNetworkError, applyCallerFeatureFlagOverrides = (target, callerProperties) => {
- for (const key of Object.keys(callerProperties))
- if (key.startsWith("$feature/") || key === "$active_feature_flags")
- target[key] = callerProperties[key];
-}, DEFAULT_QUEUE_ROUTE = "default";
-var init_posthog_core_stateless = __esm(() => {
- init_eventemitter();
- init_featureFlagUtils();
- init_gzip();
- init_types7();
+var MAX_RETRIES_PER_BATCH = 8;
+var init_traces = __esm(() => {
+ init_span();
+ init_ids();
+ init_traceparent();
+ init_sanitize();
+ init_json_utils();
+ init_otlp();
init_utils();
- init_uuidv7();
- init_error_tracking();
- PostHogFetchHttpError = class PostHogFetchHttpError extends Error {
- constructor(response, reqByteLength, responseBodyDeadline, abortController) {
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
- }
- get status() {
- return this.response.status;
- }
- get bodyReadTimedOut() {
- return this._bodyReadTimedOut;
- }
- get text() {
- if (!this.responseBodyTextPromise)
- if (Date.now() >= this.responseBodyDeadline) {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- this.cancelResponseBody(timeoutError);
- this.responseBodyTextPromise = Promise.reject(timeoutError);
- } else {
- const responseBodyTimeout = new Promise((_resolve, reject) => {
- this.responseBodyTimer = safeSetTimeout(() => {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- reject(timeoutError);
- this.cancelResponseBody(timeoutError);
- }, this.responseBodyDeadline - Date.now());
- });
- let responseBodyText;
- try {
- responseBodyText = Promise.resolve(this.response.text());
- } catch (error) {
- responseBodyText = Promise.reject(error);
- }
- this.responseBodyTextPromise = Promise.race([
- responseBodyText,
- responseBodyTimeout
- ]).finally(() => clearTimeout(this.responseBodyTimer));
- }
- return this.responseBodyTextPromise;
- }
- get json() {
- return this.text.then((text) => JSON.parse(text));
- }
- cancelResponseBody(reason) {
- clearTimeout(this.responseBodyTimer);
- if (!this.abortController.signal.aborted)
- this.abortController.abort(reason);
- (async () => {
- try {
- await this.response.body?.cancel();
- } catch {}
- })();
- }
- };
- PostHogFetchNetworkError = class PostHogFetchNetworkError extends Error {
- constructor(error) {
- super("Network error while fetching PostHog", error instanceof Error ? {
- cause: error
- } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+ init_flush_timer();
+ init_retry_after();
+ init_backoff();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/context.mjs
+class SyncSpanContextManager {
+ active() {
+ return this._active;
+ }
+ with(span, fn) {
+ const previous = this._active;
+ this._active = span;
+ try {
+ return fn();
+ } finally {
+ this._active = previous;
}
+ }
+}
+var init_context = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/config.mjs
+function positiveInteger(value, fallback) {
+ return typeof value == "number" && Number.isInteger(value) && value >= 1 ? value : fallback;
+}
+function withUsableIdentityKeys(attributes) {
+ if (!attributes || typeof attributes != "object" || Array.isArray(attributes))
+ return;
+ try {
+ if (IDENTITY_KEYS.every((key) => !(key in attributes) || typeof attributes[key] == "string"))
+ return attributes;
+ const usable = {
+ ...attributes
+ };
+ for (const key of IDENTITY_KEYS)
+ if (key in usable && typeof usable[key] != "string")
+ delete usable[key];
+ return usable;
+ } catch {
+ return;
+ }
+}
+function resolveBeforeSpanSend(beforeSpanSend, logger) {
+ if (!beforeSpanSend)
+ return [];
+ const supplied = [
+ beforeSpanSend
+ ].flat().filter((hook) => Boolean(hook));
+ const hooks = supplied.filter((hook) => typeof hook == "function");
+ if (hooks.length !== supplied.length)
+ logger?.critical(`beforeSpanSend: ignoring ${supplied.length - hooks.length} of ${supplied.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);
+ return hooks;
+}
+function resolveTracesConfig(config, hostResourceAttributes, logger) {
+ const resourceAttributes = assignUserAttributes({
+ ...hostResourceAttributes
+ }, withUsableIdentityKeys(config?.resourceAttributes));
+ const maxExportBatchSize = positiveInteger(config?.maxExportBatchSize, DEFAULT_MAX_EXPORT_BATCH_SIZE);
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSpanSend: resolveBeforeSpanSend(config?.beforeSpanSend, logger),
+ maxAttributesPerSpan: positiveInteger(config?.maxAttributesPerSpan, DEFAULT_MAX_ATTRIBUTES_PER_SPAN),
+ maxEventsPerSpan: positiveInteger(config?.maxEventsPerSpan, DEFAULT_MAX_EVENTS_PER_SPAN),
+ maxAttributesPerEvent: DEFAULT_MAX_ATTRIBUTES_PER_EVENT,
+ maxAttributeValueLength: positiveInteger(config?.maxAttributeValueLength, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH),
+ flushIntervalMs: positiveInteger(config?.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS2),
+ maxExportBatchSize,
+ maxQueueSize: Math.max(positiveInteger(config?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE), maxExportBatchSize),
+ maxLiveSpans: positiveInteger(config?.maxLiveSpans, DEFAULT_MAX_LIVE_SPANS),
+ maxSpanAgeMs: positiveInteger(config?.maxSpanAgeMs, DEFAULT_MAX_SPAN_AGE_MS)
};
+}
+var DEFAULT_FLUSH_INTERVAL_MS2 = 5000, DEFAULT_MAX_EXPORT_BATCH_SIZE = 512, DEFAULT_MAX_QUEUE_SIZE = 2048, DEFAULT_MAX_ATTRIBUTES_PER_SPAN = 128, DEFAULT_MAX_EVENTS_PER_SPAN = 128, DEFAULT_MAX_ATTRIBUTES_PER_EVENT = 128, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 8192, DEFAULT_MAX_LIVE_SPANS = 1e4, DEFAULT_MAX_SPAN_AGE_MS = 3600000, IDENTITY_KEYS;
+var init_config3 = __esm(() => {
+ init_json_utils();
+ IDENTITY_KEYS = [
+ "service.name",
+ "service.version",
+ "deployment.environment"
+ ];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core.mjs
-var init_posthog_core = __esm(() => {
- init_featureFlagUtils();
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/surveys/validation.mjs
+var init_validation = __esm(() => {
init_types7();
- init_posthog_core_stateless();
- init_uuidv7();
- init_utils();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/tracing-headers.mjs
-var init_tracing_headers = __esm(() => {
- init_type_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/index.mjs
var init_dist2 = __esm(() => {
+ init_error_tracking();
init_featureFlagUtils();
+ init_featureFlagLocalEvaluation();
init_gzip();
init_logs_utils();
+ init_otlp_any_value();
+ init_otlp_resource();
init_logs();
init_metrics();
+ init_traces();
+ init_context();
+ init_span();
+ init_config3();
init_uuidv7();
init_validation();
- init_error_tracking();
init_utils();
init_cookie();
init_posthog_core();
@@ -81079,7 +84764,7 @@ var init_dist2 = __esm(() => {
init_types7();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
import { constants as constants6 } from "node:fs";
import { open as promises_open } from "node:fs/promises";
import { isAbsolute as isAbsolute7 } from "node:path";
@@ -81366,7 +85051,7 @@ var init_context_lines_node = __esm(() => {
LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
import { isAbsolute as isAbsolute8, relative as relative4, sep as sep8 } from "path";
function createRelativePathModifier(basePath = process.cwd()) {
const isWindows = sep8 === "\\";
@@ -81383,11 +85068,11 @@ function createRelativePathModifier(basePath = process.cwd()) {
}
var init_relative_path_node = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
-var version2 = "5.51.1";
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
+var version2 = "5.52.4";
var init_version = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
var FeatureFlagError2;
var init_types9 = __esm(() => {
FeatureFlagError2 = {
@@ -81398,7 +85083,7 @@ var init_types9 = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
class FeatureFlagEvaluations {
constructor(init) {
this._host = init.host;
@@ -81534,18 +85219,7 @@ var init_feature_flag_evaluations = __esm(() => {
init_types9();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
-async function hashSHA1(text) {
- const subtle = globalThis.crypto?.subtle;
- if (!subtle)
- throw new Error("SubtleCrypto API not available");
- const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
-}
-var init_crypto = () => {};
-
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
function setCustomErrorPrototype(error, constructor) {
error.name = constructor.name;
Error.captureStackTrace(error, constructor);
@@ -81558,6 +85232,7 @@ class FeatureFlagsPoller {
this.shouldBeginExponentialBackoff = false;
this.backOffCount = 0;
this.pollerStopped = false;
+ this.filteredOutFlagKeys = new Set;
this.pollingInterval = pollingInterval;
this.personalApiKey = personalApiKey;
this.featureFlags = [];
@@ -81576,6 +85251,7 @@ class FeatureFlagsPoller {
this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
this.cacheProvider = options.cacheProvider;
this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
+ this.evaluationContexts = options.evaluationContexts;
this.loadFeatureFlags();
}
debug(enabled = true) {
@@ -81707,23 +85383,7 @@ class FeatureFlagsPoller {
return distinctId;
}
getFeatureFlagPayload(key, flagValue) {
- let payload = null;
- if (flagValue !== false && flagValue != null) {
- if (typeof flagValue == "boolean")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
- else if (typeof flagValue == "string")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
- if (payload != null) {
- if (typeof payload == "object")
- return payload;
- if (typeof payload == "string")
- try {
- return JSON.parse(payload);
- } catch {}
- return payload;
- }
- }
- return null;
+ return resolveFeatureFlagPayload(this.featureFlagsByKey?.[key]?.filters?.payloads, flagValue);
}
async evaluateFlagDependency(property, properties, evaluationContext) {
const { evaluationCache } = evaluationContext;
@@ -81750,6 +85410,8 @@ class FeatureFlagsPoller {
}
else
evaluationCache[depFlagKey] = false;
+ else if (this.filteredOutFlagKeys.has(depFlagKey))
+ evaluationCache[depFlagKey] = false;
else
throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
}
@@ -81802,8 +85464,11 @@ class FeatureFlagsPoller {
result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
break;
}
- if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound") {
+ if (isInconclusive)
+ break;
return false;
+ }
} catch (e) {
if (e instanceof RequiresServerEvaluation)
throw e;
@@ -81838,36 +85503,33 @@ class FeatureFlagsPoller {
if (rolloutPercentage == undefined)
return "match";
}
- if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
+ if (rolloutPercentage != null && await getFeatureFlagHash(flag.key, bucketingValue) > rolloutPercentage / 100)
return "out_of_rollout_bound";
return "match";
}
async getMatchingVariant(flag, bucketingValue) {
- const hashValue = await _hash(flag.key, bucketingValue, "variant");
- const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
- if (matchingVariant)
- return matchingVariant.key;
+ return getFeatureFlagVariant(flag.key, bucketingValue, flag.filters?.multivariate?.variants || []);
}
variantLookupTable(flag) {
- const lookupTable = [];
- let valueMin = 0;
- let valueMax = 0;
- const flagFilters = flag.filters || {};
- const multivariates = flagFilters.multivariate?.variants || [];
- multivariates.forEach((variant) => {
- valueMax = valueMin + variant.rollout_percentage / 100;
- lookupTable.push({
- valueMin,
- valueMax,
- key: variant.key
- });
- valueMin = valueMax;
+ return getFeatureFlagVariantLookupTable(flag.filters?.multivariate?.variants || []);
+ }
+ filterFlagsByEvaluationContexts(flags) {
+ if (!this.evaluationContexts || this.evaluationContexts.length === 0)
+ return flags;
+ const contexts = new Set(this.evaluationContexts);
+ return flags.filter((flag) => {
+ const tags = flag.evaluation_contexts ?? flag.evaluation_tags;
+ if (!tags || tags.length === 0)
+ return true;
+ return tags.some((tag) => contexts.has(tag));
});
- return lookupTable;
}
updateFlagState(flagData) {
- this.featureFlags = flagData.flags;
- this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const flags = this.filterFlagsByEvaluationContexts(flagData.flags);
+ this.featureFlags = flags;
+ this.featureFlagsByKey = flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const keptKeys = new Set(flags.map((flag) => flag.key));
+ this.filteredOutFlagKeys = new Set(flagData.flags.filter((flag) => !keptKeys.has(flag.key)).map((flag) => flag.key));
this.groupTypeMapping = flagData.groupTypeMapping;
this.cohorts = flagData.cohorts;
this.loadedSuccessfullyOnce = true;
@@ -81889,7 +85551,7 @@ class FeatureFlagsPoller {
this.updateFlagState(cached);
this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(cached.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
return true;
}
return false;
@@ -81967,6 +85629,7 @@ class FeatureFlagsPoller {
console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
this.featureFlags = [];
this.featureFlagsByKey = {};
+ this.filteredOutFlagKeys = new Set;
this.groupTypeMapping = {};
this.cohorts = {};
this.onMinimalFlagCalledEvents?.(false);
@@ -81998,7 +85661,7 @@ class FeatureFlagsPoller {
this.onError?.(new Error(`Failed to store in cache: ${err}`));
}
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(flagData.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
break;
}
default:
@@ -82084,136 +85747,10 @@ class FeatureFlagsPoller {
}
}
}
-async function _hash(key, bucketingValue, salt = "") {
- const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
- return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
-}
function matchProperty(property, propertyValues, warnFunction) {
- const key = property.key;
- const value = property.value;
- const operator = property.operator || "exact";
- if (key in propertyValues) {
- if (operator === "is_not_set")
- return false;
- } else {
- if (operator === "is_not_set")
- return true;
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
- }
- const overrideValue = propertyValues[key];
- if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
- if (warnFunction)
- warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
- return false;
- }
- function computeExactMatch(value, overrideValue) {
- if (Array.isArray(value))
- return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
- return String(value).toLowerCase() === String(overrideValue).toLowerCase();
- }
- function compare(lhs, rhs, operator) {
- if (operator === "gt")
- return lhs > rhs;
- if (operator === "gte")
- return lhs >= rhs;
- if (operator === "lt")
- return lhs < rhs;
- if (operator === "lte")
- return lhs <= rhs;
- throw new Error(`Invalid operator: ${operator}`);
- }
- switch (operator) {
- case "exact":
- return computeExactMatch(value, overrideValue);
- case "is_not":
- return !computeExactMatch(value, overrideValue);
- case "is_set":
- return key in propertyValues;
- case "icontains":
- return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "not_icontains":
- return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "starts_with":
- return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "not_starts_with":
- return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "ends_with":
- return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "not_ends_with":
- return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
- case "not_regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
- case "gt":
- case "gte":
- case "lt":
- case "lte": {
- const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
- let parsedOverride;
- parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : NaN;
- if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
- return compare(parsedOverride, parsedValue, operator);
- return compare(String(overrideValue), String(value), operator);
- }
- case "is_date_after":
- case "is_date_before": {
- if (typeof value == "boolean")
- throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
- if (parsedDate == null)
- parsedDate = convertToDateTime(value);
- if (parsedDate == null)
- throw new InconclusiveMatchError(`Invalid date: ${value}`);
- const overrideDate = convertToDateTime(overrideValue);
- if ([
- "is_date_before"
- ].includes(operator))
- return overrideDate < parsedDate;
- return overrideDate > parsedDate;
- }
- case "semver_eq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp === 0;
- }
- case "semver_neq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp !== 0;
- }
- case "semver_gt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp > 0;
- }
- case "semver_gte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp >= 0;
- }
- case "semver_lt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp < 0;
- }
- case "semver_lte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp <= 0;
- }
- case "semver_tilde": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeTildeBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_caret": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeCaretBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_wildcard": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeWildcardBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- default:
- throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
- }
+ return matchFeatureFlagProperty(property, propertyValues, {
+ warnFunction
+ });
}
function checkCohortExists(cohortId, cohortProperties) {
if (!(cohortId in cohortProperties))
@@ -82293,187 +85830,9 @@ async function matchPropertyGroup(propertyGroup, propertyValues, cohortPropertie
throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
return propertyGroupType === "AND";
}
-function isValidRegex(regex) {
- try {
- new RegExp(regex);
- return true;
- } catch (err) {
- return false;
- }
-}
-function parseSemverNumericIdentifier(part, raw) {
- if (!/^\d+$/.test(part))
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- if (part.length > 1 && part[0] === "0")
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- return parseInt(part, 10);
-}
-function parseSemver(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const baseVersion = text.split("-")[0].split("+")[0];
- if (!baseVersion || baseVersion.startsWith("."))
- throw new InconclusiveMatchError(`Invalid semver: ${value}`);
- const parts = baseVersion.split(".");
- const parsePart = (part) => {
- if (part === undefined || part === "")
- return 0;
- return parseSemverNumericIdentifier(part, value);
- };
- const major = parsePart(parts[0]);
- const minor = parsePart(parts[1]);
- const patch = parsePart(parts[2]);
- return [
- major,
- minor,
- patch
- ];
-}
-function compareSemverTuples(a, b) {
- for (let i = 0;i < 3; i++) {
- if (a[i] < b[i])
- return -1;
- if (a[i] > b[i])
- return 1;
- }
- return 0;
-}
-function computeTildeBounds(value) {
- const parsed = parseSemver(value);
- const lower = [
- parsed[0],
- parsed[1],
- parsed[2]
- ];
- const upper = [
- parsed[0],
- parsed[1] + 1,
- 0
- ];
- return {
- lower,
- upper
- };
-}
-function computeCaretBounds(value) {
- const parsed = parseSemver(value);
- const [major, minor, patch] = parsed;
- const lower = [
- major,
- minor,
- patch
- ];
- let upper;
- upper = major > 0 ? [
- major + 1,
- 0,
- 0
- ] : minor > 0 ? [
- 0,
- minor + 1,
- 0
- ] : [
- 0,
- 0,
- patch + 1
- ];
- return {
- lower,
- upper
- };
-}
-function computeWildcardBounds(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
- if (!cleanedText)
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- const parts = cleanedText.split(".");
- const parseWildcardPart = (part) => {
- try {
- return parseSemverNumericIdentifier(part, value);
- } catch {
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- }
- };
- const major = parseWildcardPart(parts[0]);
- let lower;
- let upper;
- if (parts.length === 1) {
- lower = [
- major,
- 0,
- 0
- ];
- upper = [
- major + 1,
- 0,
- 0
- ];
- } else {
- const minor = parseWildcardPart(parts[1]);
- lower = [
- major,
- minor,
- 0
- ];
- upper = [
- major,
- minor + 1,
- 0
- ];
- }
- return {
- lower,
- upper
- };
-}
-function convertToDateTime(value) {
- if (value instanceof Date)
- return value;
- if (typeof value == "string" || typeof value == "number") {
- const date = new Date(value);
- if (!isNaN(date.valueOf()))
- return date;
- throw new InconclusiveMatchError(`${value} is in an invalid date format`);
- }
- throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
-}
-function relativeDateParseForFeatureFlagMatching(value) {
- const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
- const match = value.match(regex);
- const parsedDt = new Date(new Date().toISOString());
- if (!match)
- return null;
- {
- if (!match.groups)
- return null;
- const number = parseInt(match.groups["number"]);
- if (number >= 1e4)
- return null;
- const interval = match.groups["interval"];
- if (interval == "h")
- parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
- else if (interval == "d")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
- else if (interval == "w")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
- else if (interval == "m")
- parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
- else {
- if (interval != "y")
- return null;
- parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
- }
- return parsedDt;
- }
-}
-var SIXTY_SECONDS = 60000, LONG_SCALE = 1152921504606847000, NULL_VALUES_ALLOWED_OPERATORS, ClientError, InconclusiveMatchError, RequiresServerEvaluation;
+var SIXTY_SECONDS = 60000, ClientError, RequiresServerEvaluation;
var init_feature_flags = __esm(() => {
init_dist2();
- init_crypto();
- NULL_VALUES_ALLOWED_OPERATORS = [
- "is_not",
- "is_set"
- ];
ClientError = class ClientError extends Error {
constructor(message) {
super();
@@ -82483,12 +85842,6 @@ var init_feature_flags = __esm(() => {
Object.setPrototypeOf(this, ClientError.prototype);
}
};
- InconclusiveMatchError = class InconclusiveMatchError extends Error {
- constructor(message) {
- super(message);
- setCustomErrorPrototype(this, InconclusiveMatchError);
- }
- };
RequiresServerEvaluation = class RequiresServerEvaluation extends Error {
constructor(message) {
super(message);
@@ -82497,7 +85850,7 @@ var init_feature_flags = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
function splitNodeOptions(nodeOptions) {
const args = [];
let current = "";
@@ -82598,7 +85951,7 @@ var init_autocapture = __esm(() => {
STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
class error_tracking_ErrorTracking {
constructor(client, options, _logger) {
this.client = client;
@@ -82666,13 +86019,14 @@ class error_tracking_ErrorTracking {
this._rateLimiter.stop();
}
}
-var SHUTDOWN_TIMEOUT = 2000;
+var SHUTDOWN_TIMEOUT = 2000, error_tracking_default;
var init_error_tracking2 = __esm(() => {
init_autocapture();
init_dist2();
+ error_tracking_default = error_tracking_ErrorTracking;
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
class PostHogMemoryStorage {
getProperty(key) {
return this._memoryStorage[key];
@@ -82686,24 +86040,24 @@ class PostHogMemoryStorage {
}
var init_storage_memory = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
function isCaptureMode(value) {
return value === "v0" || value === "v1";
}
function resolveCaptureMode() {
- const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
+ const envMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
return isCaptureMode(envMode) ? envMode : "v0";
}
-var init_config3 = () => {};
+var init_config4 = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
function isLegacyOnlyEvent(message) {
return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
}
var AI_EVENT_PREFIX = "$ai_", ANALYTICS_ROUTE = "analytics", AI_ROUTE = "ai";
var init_routing = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
var CaptureV1Error;
var init_errors3 = __esm(() => {
CaptureV1Error = class CaptureV1Error extends Error {
@@ -82723,7 +86077,7 @@ var init_errors3 = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
function coerceBool(value) {
if (typeof value == "boolean")
return value;
@@ -82841,7 +86195,7 @@ var init_transform = __esm(() => {
];
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
class V1CaptureSender {
constructor(config, hooks) {
this.config = config;
@@ -83097,11 +86451,11 @@ var init_sender = __esm(() => {
]);
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
var AI_CAPTURE_ROUTE = "ai-capture", AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/", AI_MAX_EVENT_BYTES = 8388608, AI_BATCH_TARGET_BYTES = 5242880;
var init_routing2 = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
function eventByteSize(message) {
return encoder.encode(safeJsonStringify(message)).length;
}
@@ -83143,7 +86497,7 @@ var init_batching = __esm(() => {
encoder = new TextEncoder;
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
function emitDeprecationWarningOnce(id, message) {
if (_emittedDeprecations.has(id))
return;
@@ -83187,7 +86541,7 @@ var init_client3 = __esm(() => {
init_feature_flags();
init_error_tracking2();
init_storage_memory();
- init_config3();
+ init_config4();
init_routing();
init_sender();
init_batching();
@@ -83236,10 +86590,11 @@ var init_client3 = __esm(() => {
},
customHeaders: this.getCustomHeaders(),
cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
- strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
+ strictLocalEvaluation: normalizedOptions.strictLocalEvaluation,
+ evaluationContexts: normalizedOptions.evaluationContexts ?? normalizedOptions.evaluationEnvironments
});
}
- this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
+ this.errorTracking = new error_tracking_default(this, normalizedOptions, this._logger);
this.distinctIdHasSentFlagCalls = {};
this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
}
@@ -83247,8 +86602,26 @@ var init_client3 = __esm(() => {
super.enqueue(type, message, options, explicitRoute);
this.scheduleDebouncedFlush();
}
+ _flushEventsAndSpans(skipThrottledSpans = false) {
+ const events = this.flushWithPendingPromises();
+ if (!this._traces || skipThrottledSpans && this._traces.throttled)
+ return events;
+ return allSettled([
+ events,
+ this._traces.flush().catch(() => {})
+ ]).then(([eventsResult]) => {
+ if (eventsResult.status === "rejected")
+ throw eventsResult.reason;
+ });
+ }
+ flushAutomatic() {
+ return this._flushKeepingRuntimeAlive(true);
+ }
async flush() {
- const flushPromise = this.flushWithPendingPromises();
+ return this._flushKeepingRuntimeAlive(false);
+ }
+ _flushKeepingRuntimeAlive(skipThrottledSpans) {
+ const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
const waitUntil = this.options.waitUntil;
if (waitUntil && !this._waitUntilCycle)
try {
@@ -83301,7 +86674,7 @@ var init_client3 = __esm(() => {
async resolveWaitUntilFlush() {
const resolve = this._consumeWaitUntilCycle();
try {
- await this.flushWithPendingPromises();
+ await this._flushEventsAndSpans();
} catch {} finally {
resolve?.();
}
@@ -83403,9 +86776,51 @@ var init_client3 = __esm(() => {
this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
return this._metrics;
}
+ initializeSpanContextManager() {
+ return new SyncSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return {};
+ }
+ get _spanContextManager() {
+ if (!this._spanContext)
+ this._spanContext = this.initializeSpanContextManager();
+ return this._spanContext;
+ }
+ get _tracesPipeline() {
+ if (!this.options.traces)
+ return;
+ if (!this._traces)
+ this._traces = new PostHogTraces(this, resolveTracesConfig(this.options.traces, this.hostResourceAttributes(), this._logger), this._logger, () => this._tracingContext(), this._spanContextManager, () => this.scheduleDebouncedFlush());
+ return this._traces;
+ }
+ _tracingContext() {
+ const context = this.context?.get();
+ return {
+ distinctId: context?.distinctId,
+ sessionId: context?.sessionId
+ };
+ }
+ startSpan(name, options) {
+ return this._tracesPipeline?.startSpan(name, options) ?? inertSpan(options, this._spanContextManager.active());
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const pipeline = this._tracesPipeline;
+ if (!pipeline)
+ return runWithActiveSpan(this._spanContextManager, inertSpan(options, this._spanContextManager.active()), fn);
+ return options ? pipeline.withSpan(name, options, fn) : pipeline.withSpan(name, fn);
+ }
+ getActiveSpan() {
+ return this._spanContextManager.active() ?? null;
+ }
getCustomUserAgent() {
return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
}
+ getEvaluationRuntime() {
+ return "server";
+ }
getCommonEventProperties() {
const commonProperties = super.getCommonEventProperties();
if (this.options.isServer ?? true)
@@ -83893,7 +87308,16 @@ var init_client3 = __esm(() => {
flags: {}
});
}
- const { groups, disableGeoip, flagKeys } = resolvedOptions || {};
+ const { groups, disableGeoip } = resolvedOptions || {};
+ const flagKeys = resolvedOptions?.flagKeys ?? undefined;
+ if (flagKeys?.length === 0)
+ return new FeatureFlagEvaluations({
+ host: this._getFeatureFlagEvaluationsHost(),
+ distinctId: resolvedDistinctId,
+ groups,
+ disableGeoip,
+ flags: {}
+ });
let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};
const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
personProperties = adjustedProperties.allPersonProperties;
@@ -84147,6 +87571,10 @@ var init_client3 = __esm(() => {
await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
this._metrics.reset();
}
+ if (this._traces) {
+ await raceWithTimeout(this._traces.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
+ this._traces.reset();
+ }
try {
return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
} finally {
@@ -84275,9 +87703,9 @@ var init_client3 = __esm(() => {
};
}
captureException(error, distinctId, additionalProperties, uuid, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
...msg,
@@ -84287,9 +87715,9 @@ var init_client3 = __esm(() => {
}
}
async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ return this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this.captureImmediate({
...msg,
@@ -84400,7 +87828,7 @@ var init_client3 = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
import { AsyncLocalStorage } from "node:async_hooks";
class PostHogContext {
@@ -84430,9 +87858,25 @@ class PostHogContext {
};
}
}
-var init_context = () => {};
+var init_context2 = () => {};
+
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/span-context.node.mjs
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
+
+class AsyncLocalStorageSpanContextManager {
+ active() {
+ return this._storage.getStore();
+ }
+ with(span, fn) {
+ return this._storage.run(span, fn);
+ }
+ constructor() {
+ this._storage = new AsyncLocalStorage2;
+ }
+}
+var init_span_context_node = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
import { gzip } from "node:zlib";
import { promisify } from "node:util";
async function gzipCompress2(input, isDebug = true) {
@@ -84450,7 +87894,22 @@ var init_gzip_node = __esm(() => {
gzipAsync = promisify(gzip);
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/host-os.node.mjs
+import { platform, release as release2 } from "node:os";
+function hostOsResourceAttributes() {
+ let osName;
+ let osVersion;
+ try {
+ osName = platform();
+ osVersion = release2();
+ } catch {}
+ return osResourceAttributes(osName, osVersion);
+}
+var init_host_os_node = __esm(() => {
+ init_dist2();
+});
+
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
"error"
], sendExceptionsToPostHog = true } = {}) {
@@ -84507,7 +87966,9 @@ var NAME = "posthog-node", PostHogSentryIntegration;
var init_sentry_integration = __esm(() => {
init_dist2();
PostHogSentryIntegration = class PostHogSentryIntegration {
- static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ static {
+ this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ }
constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
this.name = NAME;
this.name = NAME;
@@ -84525,22 +87986,22 @@ var init_sentry_integration = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
var init_tracing_headers2 = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/url-utils.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/url-utils.mjs
var init_url_utils = __esm(() => {
init_dist2();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/express.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/express.mjs
var init_express = __esm(() => {
init_error_tracking2();
init_tracing_headers2();
init_url_utils();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/exports.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/exports.mjs
var init_exports = __esm(() => {
init_feature_flag_evaluations();
init_dist2();
@@ -84549,7 +88010,7 @@ var init_exports = __esm(() => {
init_types9();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
var PostHog;
var init_index_node = __esm(() => {
init_module_node();
@@ -84557,8 +88018,10 @@ var init_index_node = __esm(() => {
init_relative_path_node();
init_client3();
init_dist2();
- init_context();
+ init_context2();
+ init_span_context_node();
init_gzip_node();
+ init_host_os_node();
init_exports();
PostHog = class PostHog extends PostHogBackendClient {
getLibraryId() {
@@ -84570,6 +88033,12 @@ var init_index_node = __esm(() => {
initializeContext() {
return new PostHogContext;
}
+ initializeSpanContextManager() {
+ return new AsyncLocalStorageSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return hostOsResourceAttributes();
+ }
createErrorPropertiesBuilder() {
return new ErrorPropertiesBuilder([
new EventCoercer,
@@ -84792,7 +88261,7 @@ var package_default2;
var init_package2 = __esm(() => {
package_default2 = {
name: "@oh-my-opencode/omo-codex",
- version: "5.0.0-beta.80",
+ version: "5.0.0-beta.81",
type: "module",
private: true,
description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -94555,7 +98024,7 @@ function isYes(value) {
return normalized === "y" || normalized === "yes";
}
-// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
import { stdout, stdin } from "node:process";
import * as l from "node:readline";
import l__default from "node:readline";
@@ -94901,7 +98370,7 @@ function wrapAnsi(string, columns, options) {
`);
}
-// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
var import_sisteransi = __toESM(require_src(), 1);
import { ReadStream } from "node:tty";
function findCursor(s, o, l) {
@@ -94940,6 +98409,7 @@ var settings = {
error: "Something went wrong"
},
withGuide: true,
+ accessible: undefined,
date: {
monthNames: [...t],
messages: {
@@ -94951,6 +98421,14 @@ var settings = {
}
}
};
+function isAccessible(n) {
+ if (n !== undefined)
+ return n;
+ if (settings.accessible !== undefined)
+ return settings.accessible;
+ const e = process.env.ACCESSIBLE;
+ return e !== undefined && e !== "" && e !== "0" && e !== "false";
+}
function isActionKey(n, e) {
if (typeof n == "string")
return settings.aliases.get(n) === e;
@@ -94987,7 +98465,7 @@ function block({
input: e = stdin,
output: r = stdout,
overwrite: o = true,
- hideCursor: t = true
+ hideCursor: n = true
} = {}) {
const s = l.createInterface({
input: e,
@@ -94996,10 +98474,10 @@ function block({
tabSize: 1
});
l.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
- const n = (f, { name: a, sequence: p }) => {
+ const t = (f, { name: a, sequence: w }) => {
const c = String(f);
- if (isActionKey([c, a, p], "cancel")) {
- t && r.write(import_sisteransi.cursor.show), process.exit(0);
+ if (isActionKey([c, a, w], "cancel")) {
+ n && r.write(import_sisteransi.cursor.show), process.exit(0);
return;
}
if (!o)
@@ -95007,39 +98485,37 @@ function block({
const i = a === "return" ? 0 : -1, m = a === "return" ? -1 : 0;
l.moveCursor(r, i, m, () => {
l.clearLine(r, 1, () => {
- e.once("keypress", n);
+ e.once("keypress", t);
});
});
};
- return t && r.write(import_sisteransi.cursor.hide), e.once("keypress", n), () => {
- e.off("keypress", n), t && r.write(import_sisteransi.cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
+ return n && r.write(import_sisteransi.cursor.hide), e.once("keypress", t), () => {
+ e.off("keypress", t), n && r.write(import_sisteransi.cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
};
}
var getColumns = (e) => ("columns" in e) && typeof e.columns == "number" ? e.columns : 80;
var getRows = (e) => ("rows" in e) && typeof e.rows == "number" ? e.rows : 20;
-function wrapTextWithPrefix(e, r, o, t = o, s = o, n) {
+function wrapTextWithPrefix(e, r, o, n = o, s = o, t) {
const f = getColumns(e ?? stdout);
return wrapAnsi(r, f - o.length, {
hard: true,
trim: false
}).split(`
`).map((c, i, m) => {
- const d = n ? n(c, i) : c;
- return i === 0 ? `${t}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;
+ const d = t ? t(c, i) : c;
+ return i === 0 ? `${n}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;
}).join(`
`);
}
-function runValidation(e, n) {
+function runValidation(e, a) {
if ("~standard" in e) {
- const a = e["~standard"].validate(n);
- if (a instanceof Promise)
- throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");
- return a.issues?.at(0)?.message;
+ const n = e["~standard"].validate(a);
+ return n instanceof Promise ? n.then((r) => r.issues?.at(0)?.message) : n.issues?.at(0)?.message;
}
- return e(n);
+ return e(a);
}
-class V {
+class y {
input;
output;
_abortSignal;
@@ -95054,9 +98530,12 @@ class V {
error = "";
value;
userInput = "";
+ get accessible() {
+ return isAccessible(this.opts.accessible);
+ }
constructor(t, e = true) {
- const { input: i = stdin, output: n = stdout, render: s, signal: r, ...o } = t;
- this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = s.bind(this), this._track = e, this._abortSignal = r, this.input = i, this.output = n;
+ const { input: i = stdin, output: s = stdout, render: r, signal: n, ...o } = t;
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r.bind(this), this._track = e, this._abortSignal = n, this.input = i, this.output = s;
}
unsubscribe() {
this._subscribers.clear();
@@ -95072,11 +98551,11 @@ class V {
this.setSubscriber(t, { cb: e, once: true });
}
emit(t, ...e) {
- const i = this._subscribers.get(t) ?? [], n = [];
- for (const s of i)
- s.cb(...e), s.once && n.push(() => i.splice(i.indexOf(s), 1));
- for (const s of n)
- s();
+ const i = this._subscribers.get(t) ?? [], s = [];
+ for (const r of i)
+ r.cb(...e), r.once && s.push(() => i.splice(i.indexOf(r), 1));
+ for (const r of s)
+ r();
}
prompt() {
return new Promise((t) => {
@@ -95115,15 +98594,18 @@ class V {
_clearUserInput() {
this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
}
- onKeypress(t, e) {
- if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
- if (this.opts.validate) {
- const i = runValidation(this.opts.validate, this.value);
- i && (this.error = i instanceof Error ? i.message : i, this.state = "error", this.rl?.write(this.userInput));
+ async onKeypress(t, e) {
+ if (this.state !== "validating") {
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
+ if (this.opts.validate) {
+ const i = runValidation(this.opts.validate, this.value);
+ let s;
+ i instanceof Promise ? (this.state = "validating", this.render(), s = await i) : s = i, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
+ }
+ this.state !== "error" && (this.state = "submit");
}
- this.state !== "error" && (this.state = "submit");
+ isActionKey([t, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
}
- isActionKey([t, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
}
close() {
this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
@@ -95145,28 +98627,28 @@ class V {
else {
const e = diffLines(this._prevFrame, t), i = getRows(this.output);
if (this.restoreCursor(), e) {
- const n = Math.max(0, e.numLinesAfter - i), s = Math.max(0, e.numLinesBefore - i);
- let r = e.lines.find((o) => o >= n);
- if (r === undefined) {
+ const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);
+ let n = e.lines.find((o) => o >= s);
+ if (n === undefined) {
this._prevFrame = t;
return;
}
if (e.lines.length === 1) {
- this.output.write(import_sisteransi.cursor.move(0, r - s)), this.output.write(import_sisteransi.erase.lines(1));
+ this.output.write(import_sisteransi.cursor.move(0, n - r)), this.output.write(import_sisteransi.erase.lines(1));
const o = t.split(`
`);
- this.output.write(o[r]), this._prevFrame = t, this.output.write(import_sisteransi.cursor.move(0, o.length - r - 1));
+ this.output.write(o[n]), this._prevFrame = t, this.output.write(import_sisteransi.cursor.move(0, o.length - n - 1));
return;
} else if (e.lines.length > 1) {
- if (n < s)
- r = n;
+ if (s < r)
+ n = s;
else {
- const h = r - s;
+ const h = n - r;
h > 0 && this.output.write(import_sisteransi.cursor.move(0, h));
}
this.output.write(import_sisteransi.erase.down());
const f = t.split(`
-`).slice(r);
+`).slice(n);
this.output.write(f.join(`
`)), this._prevFrame = t;
return;
@@ -95178,7 +98660,7 @@ class V {
}
}
}
-class r extends V {
+class r extends y {
get cursor() {
return this.value ? 0 : 1;
}
@@ -95195,7 +98677,7 @@ class r extends V {
});
}
}
-var n$1 = class n extends V {
+var n$1 = class n extends y {
options;
cursor = 0;
get _selectedValue() {
@@ -95224,7 +98706,7 @@ var n$1 = class n extends V {
}
};
-// node_modules/.bun/@[email protected]/node_modules/@clack/prompts/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@clack/prompts/dist/index.mjs
import { styleText, stripVTControlCharacters as stripVTControlCharacters3 } from "node:util";
import process$1 from "node:process";
var import_sisteransi2 = __toESM(require_src(), 1);
@@ -95273,6 +98755,8 @@ var symbol = (o) => {
return styleText("yellow", S_STEP_ERROR);
case "submit":
return styleText("green", S_STEP_SUBMIT);
+ case "validating":
+ return styleText("dim", S_STEP_ACTIVE);
}
};
var symbolBar = (o) => {
@@ -95347,34 +98831,34 @@ var limitOptions = ({
x.push(n);
return c && x.push(M), x;
};
-var confirm = (i) => {
- const a = i.active ?? "Yes", s = i.inactive ?? "No";
+var confirm = (e) => {
+ const a = e.active ?? "Yes", o = e.inactive ?? "No";
return new r({
active: a,
- inactive: s,
- signal: i.signal,
- input: i.input,
- output: i.output,
- initialValue: i.initialValue ?? true,
+ inactive: o,
+ signal: e.signal,
+ input: e.input,
+ output: e.output,
+ initialValue: e.initialValue ?? true,
render() {
- const e = i.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = e ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(i.output, i.message, l, u), o = `${e ? `${styleText("gray", S_BAR)}
+ const i = e.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = i ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(e.output, e.message, l, u), s = `${i ? `${styleText("gray", S_BAR)}
` : ""}${f}
-`, c = this.value ? a : s;
+`, c = this.value ? a : o;
switch (this.state) {
case "submit": {
- const r = e ? `${styleText("gray", S_BAR)} ` : "";
- return `${o}${r}${styleText("dim", c)}`;
+ const r = i ? `${styleText("gray", S_BAR)} ` : "";
+ return `${s}${r}${styleText("dim", c)}`;
}
case "cancel": {
- const r = e ? `${styleText("gray", S_BAR)} ` : "";
- return `${o}${r}${styleText(["strikethrough", "dim"], c)}${e ? `
+ const r = i ? `${styleText("gray", S_BAR)} ` : "";
+ return `${s}${r}${styleText(["strikethrough", "dim"], c)}${i ? `
${styleText("gray", S_BAR)}` : ""}`;
}
default: {
- const r = e ? `${styleText("cyan", S_BAR)} ` : "", g = e ? styleText("cyan", S_BAR_END) : "";
- return `${o}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${i.vertical ? e ? `
+ const r = i ? `${styleText("cyan", S_BAR)} ` : "", g = i ? styleText("cyan", S_BAR_END) : "";
+ return `${s}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${e.vertical ? i ? `
${styleText("cyan", S_BAR)} ` : `
-` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", s)}` : `${styleText("green", S_RADIO_ACTIVE)} ${s}`}
+` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", o)}` : `${styleText("green", S_RADIO_ACTIVE)} ${o}`}
${g}
`;
}
@@ -95604,19 +99088,19 @@ ${styleText("gray", S_BAR)}` : ""}`;
}
default: {
const r = n ? `${styleText("cyan", S_BAR)} ` : "", a = u.split(`
-`).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n) : n ? [styleText("cyan", S_BAR_END)] : [], b = p.join(`
-`), f = p.length + 1;
+`).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n) : n ? [styleText("cyan", S_BAR_END)] : [], f = p.join(`
+`), b = p.length + 1;
return `${u}${r}${limitOptions({
output: t.output,
cursor: this.cursor,
options: this.options,
maxItems: t.maxItems,
columnPadding: r.length,
- rowPadding: a + f,
+ rowPadding: a + b,
style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
}).join(`
${r}`)}
-${b}
+${f}
`;
}
}
@@ -102020,7 +105504,7 @@ var package_default3 = {
typecheck: "tsgo --noEmit -p tsconfig.json"
},
dependencies: {
- "@clack/prompts": "^1.7.0",
+ "@clack/prompts": "^1.8.1",
"@modelcontextprotocol/sdk": "^1.30.0",
"@oh-my-opencode/agents-md-core": "workspace:*",
"@oh-my-opencode/boulder-state": "workspace:*",
@@ -102041,13 +105525,13 @@ var package_default3 = {
"@oh-my-opencode/tmux-core": "workspace:*",
"@oh-my-opencode/team-core": "workspace:*",
"@oh-my-opencode/utils": "workspace:*",
- "@opencode-ai/plugin": "1.18.22",
- "@opencode-ai/sdk": "1.18.22",
+ "@opencode-ai/plugin": "1.18.31",
+ "@opencode-ai/sdk": "1.18.31",
commander: "^15.0.0",
"jsonc-parser": "^3.3.1",
picocolors: "^1.1.1",
picomatch: "^4.0.7",
- zod: "^4.4.3"
+ zod: "^4.6.5"
}
};
diff --git a/plugins/omo/dist/cli/index.js b/plugins/omo/dist/cli/index.js
index db7ebf74..1533b2aa 100755
--- a/plugins/omo/dist/cli/index.js
+++ b/plugins/omo/dist/cli/index.js
@@ -64,7 +64,7 @@ var package_default;
var init_package = __esm(() => {
package_default = {
name: "oh-my-opencode",
- version: "5.0.0-beta.80",
+ version: "5.0.0-beta.81",
description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",
main: "./dist/index.js",
types: "dist/index.d.ts",
@@ -228,25 +228,25 @@ var init_package = __esm(() => {
},
homepage: "https://github.com/code-yeongyu/oh-my-openagent#readme",
dependencies: {
- "@clack/prompts": "^1.7.0",
+ "@clack/prompts": "^1.8.1",
"@modelcontextprotocol/sdk": "^1.30.0",
- "@opencode-ai/plugin": "1.18.22",
- "@opencode-ai/sdk": "1.18.22",
- "@opentui/core": "^0.5.8",
- "@opentui/keymap": "^0.5.8",
- "@opentui/solid": "^0.5.8",
+ "@opencode-ai/plugin": "1.18.31",
+ "@opencode-ai/sdk": "1.18.31",
+ "@opentui/core": "^0.5.11",
+ "@opentui/keymap": "^0.5.11",
+ "@opentui/solid": "^0.5.11",
commander: "^15.0.0",
"detect-libc": "^2.1.2",
diff: "^9.0.0",
- "js-yaml": "^5.0.0",
+ "js-yaml": "^5.4.2",
"jsonc-parser": "^3.3.1",
picocolors: "^1.1.1",
picomatch: "^4.0.7",
- "posthog-node": "^5.51.1",
- zod: "^4.4.3"
+ "posthog-node": "^5.52.4",
+ zod: "^4.6.5"
},
devDependencies: {
- "@code-yeongyu/senpi": "2026.9.20",
+ "@code-yeongyu/senpi": "2026.9.21-2",
"@oh-my-opencode/agents-md-core": "workspace:*",
"@oh-my-opencode/ast-grep-mcp": "workspace:*",
"@oh-my-opencode/boulder-state": "workspace:*",
@@ -281,34 +281,36 @@ var init_package = __esm(() => {
"@xterm/xterm": "^6.0.0",
"bun-types": "1.4.2",
"node-pty": "^1.1.0",
- "puppeteer-core": "^25.8.0",
+ "puppeteer-core": "^25.11.0",
typescript: "^7.0.2"
},
optionalDependencies: {
- "oh-my-opencode-darwin-arm64": "5.0.0-beta.80",
- "oh-my-opencode-darwin-x64": "5.0.0-beta.80",
- "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.80",
- "oh-my-opencode-linux-arm64": "5.0.0-beta.80",
- "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64-musl": "5.0.0-beta.80",
- "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.80",
- "oh-my-opencode-windows-arm64": "5.0.0-beta.80",
- "oh-my-opencode-windows-x64": "5.0.0-beta.80",
- "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.80"
+ "oh-my-opencode-darwin-arm64": "5.0.0-beta.81",
+ "oh-my-opencode-darwin-x64": "5.0.0-beta.81",
+ "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.81",
+ "oh-my-opencode-linux-arm64": "5.0.0-beta.81",
+ "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64-musl": "5.0.0-beta.81",
+ "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.81",
+ "oh-my-opencode-windows-arm64": "5.0.0-beta.81",
+ "oh-my-opencode-windows-x64": "5.0.0-beta.81",
+ "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.81"
},
overrides: {
"@earendil-works/pi-agent-core": "0.84.2",
"@earendil-works/pi-ai": "0.84.2",
"@earendil-works/pi-coding-agent": "0.84.2",
"@earendil-works/pi-tui": "0.84.2",
- hono: "^4.12.18",
- "@hono/node-server": "^1.19.13",
- "express-rate-limit": "^8.5.1",
- "fast-uri": "^3.1.2",
+ hono: "^4.13.8",
+ "@hono/node-server": "2.1.1",
+ "express-rate-limit": "^8.7.0",
+ "fast-uri": "^3.1.6",
"path-to-regexp": "^8.4.2",
- "@types/node": "26.2.0"
+ qs: "^6.16.0",
+ "ip-address": "^10.7.2",
+ "@types/node": "26.6.2"
},
trustedDependencies: []
};
@@ -465,7 +467,7 @@ function extractSemverFromOutput(output) {
return match?.[1] ?? null;
}
-// node_modules/.bun/[email protected]/node_modules/js-yaml/dist/js-yaml.mjs
+// node_modules/.bun/[email protected]/node_modules/js-yaml/dist/js-yaml.mjs
function defineScalarTag(tagName, options) {
return {
tagName,
@@ -1206,30 +1208,38 @@ function collectionTagName(state, event, defaultTagName) {
function isMappingTag(tag) {
return tag.nodeKind === "mapping";
}
+function chargeMergeWork(state) {
+ state.totalMergeKeys++;
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys)
+ throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
+}
function mergeKeys(state, frame, source, sourceTag) {
+ chargeMergeWork(state);
for (const sourceKey of sourceTag.keys(source)) {
- if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys)
- throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
+ chargeMergeWork(state);
if (frame.tag.has(frame.value, sourceKey))
continue;
const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
if (err)
throwError$1(state, err);
- (frame.overridable ??= /* @__PURE__ */ new Set).add(sourceKey);
+ frame.overridable ??= /* @__PURE__ */ new Set;
+ frame.overridable.add(sourceKey);
}
}
function mergeSource(state, frame, source, sourceTag) {
state.position = frame.keyPosition;
if (isMappingTag(sourceTag))
mergeKeys(state, frame, source, sourceTag);
- else if (sourceTag.nodeKind === "sequence" && Array.isArray(source))
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
+ if (source.length > 100)
+ throwError$1(state, "abnormal merge sequence size");
for (const element of source) {
const elementTag = state.nodeTags.get(element);
if (!elementTag)
throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
mergeKeys(state, frame, element, elementTag);
}
- else
+ } else
throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
}
function addMappingValue(state, frame, key, value, tag) {
@@ -1577,6 +1587,27 @@ function testDocumentSeparator(state, position = state.position) {
}
return false;
}
+function skipByteOrderMark(state) {
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
+ state.position++;
+ state.lineStart = state.position;
+ }
+}
+function testDocumentBoundary(state) {
+ if (state.position !== state.lineStart)
+ return false;
+ if (testDocumentSeparator(state))
+ return true;
+ if (state.input.charCodeAt(state.position) !== 65279)
+ return false;
+ const snapshot = snapshotState(state);
+ skipByteOrderMark(state);
+ skipSeparationSpace(state, true);
+ const ch = state.input.charCodeAt(state.position);
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
+ restoreState(state, snapshot);
+ return result;
+}
function skipUntilLineEnd(state) {
let ch = state.input.charCodeAt(state.position);
while (ch !== 0 && !isEol(ch))
@@ -1804,7 +1835,7 @@ function readBlockScalar(state, parentIndent, props) {
valueEnd = linePosition + column;
break;
}
- if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition))
+ if (testDocumentBoundary(state))
break;
if (!detectedIndent && contentIndent === -1 && isEol(first))
maxLeadingIndent = Math.max(maxLeadingIndent, column);
@@ -1863,7 +1894,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
const inFlow = nodeContext === CONTEXT_FLOW_IN;
let multiline = false;
while (ch !== 0) {
- if (state.position === state.lineStart && testDocumentSeparator(state))
+ if (testDocumentBoundary(state))
break;
if (ch === 58) {
const following = state.input.charCodeAt(state.position + 1);
@@ -2301,7 +2332,7 @@ function readDocument(state) {
if (documentEvent?.type === EVENT_ID.DOCUMENT)
documentEvent.explicitEnd = explicitEnd;
addPopEvent(state);
- if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state)))
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state))
throwError(state, "end of the stream or a document separator is expected");
}
function parseEvents(input, options) {
@@ -2324,9 +2355,8 @@ function parseEvents(input, options) {
const nullpos = input.indexOf("\x00");
if (nullpos !== -1)
YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
- if (state.input.charCodeAt(state.position) === 65279)
- state.position++;
while (state.position < state.length) {
+ skipByteOrderMark(state);
skipSeparationSpace(state, true);
if (state.position >= state.length)
break;
@@ -2358,6 +2388,85 @@ function load(input, options) {
return documents[0];
throw new YAMLException("expected a single document in the stream, but found more");
}
+function hasBit(mask, bit) {
+ return (mask & 1 << bit) !== 0;
+}
+function _preferredQuotedStyle(layout) {
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED))
+ return SCALAR_STYLE.SINGLE_QUOTED;
+ return SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function applyQuoteFlowKeysOption(layout) {
+ if (!layout.presenterOptions.quoteFlowKeys)
+ return;
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN)
+ return;
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function doubleQuoteForInvisibles(layout) {
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value))
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function doubleQuoteWhitespaceOnly(layout) {
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value))
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
+function applyForceQuotesOption(layout) {
+ if (!layout.presenterOptions.forceQuotes)
+ return;
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN)
+ return;
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName)
+ return;
+ layout.style = layout.node.value.includes(`
+`) ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
+}
+function tryLongOrMultilineAsBlock(layout) {
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey)
+ return;
+ const value = layout.node.value;
+ const multiline = value.indexOf(`
+`) !== -1;
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
+ if (multiline)
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+ return;
+ }
+ const w = layout.presenterOptions.lineWidth;
+ if (w === -1) {
+ if (multiline)
+ layout.style = SCALAR_STYLE.LITERAL_BLOCK;
+ return;
+ }
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
+ let position = 0;
+ let shouldFold = false;
+ while (position <= value.length) {
+ let lineEnd = value.length;
+ const nextLineBreak = value.indexOf(`
+`, position);
+ if (nextLineBreak !== -1)
+ lineEnd = nextLineBreak;
+ const line = value.slice(position, lineEnd);
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line))
+ shouldFold = true;
+ if (nextLineBreak === -1)
+ break;
+ position = nextLineBreak + 1;
+ }
+ if (shouldFold)
+ layout.style = SCALAR_STYLE.FOLDED_BLOCK;
+ else if (multiline)
+ layout.style = SCALAR_STYLE.LITERAL_BLOCK;
+}
+function quoteInvalidPlain(layout) {
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN))
+ layout.style = _preferredQuotedStyle(layout);
+}
+function fallbackToDoubleQuoted(layout) {
+ if (!hasBit(layout.allowedStylesMask, layout.style))
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
+}
var NOT_RESOLVED, strTag, NULL_VALUES$1, nullCoreTag, nullJsonTag, NULL_VALUES, nullYaml11Tag, TRUE_VALUES$2, FALSE_VALUES$2, boolCoreTag, TRUE_VALUES$1, FALSE_VALUES$1, boolJsonTag, TRUE_VALUES, FALSE_VALUES, boolYaml11Tag, YAML_INTEGER_IMPLICIT_PATTERN$1, YAML_INTEGER_EXPLICIT_PATTERN$1, intCoreTag, YAML_INTEGER_IMPLICIT_PATTERN, YAML_INTEGER_EXPLICIT_PATTERN, intJsonTag, YAML_INTEGER_PATTERN, intYaml11Tag, YAML_FLOAT_PATTERN$1, YAML_FLOAT_SPECIAL_PATTERN$1, floatCoreTag, YAML_FLOAT_IMPLICIT_PATTERN, YAML_FLOAT_EXPLICIT_PATTERN, floatJsonTag, YAML_FLOAT_PATTERN, YAML_FLOAT_SPECIAL_PATTERN, floatYaml11Tag, mergeTag, BASE64_PATTERN, binaryTag, YAML_DATE_REGEXP, YAML_TIMESTAMP_REGEXP, timestampTag, seqTag, omapTag, pairsTag, mapTag, setTag, Schema = class Schema {
tags;
implicitScalarTags;
@@ -2468,9 +2577,9 @@ var NOT_RESOLVED, strTag, NULL_VALUES$1, nullCoreTag, nullJsonTag, NULL_VALUES,
flatTags = flatTags.concat(tag);
return new Schema([...this.tags, ...flatTags]);
}
-}, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, YAML11_SCHEMA, DUMP_SCHEMA, realMapTag, legacyMapTag, DEFAULT_SNIPPET_OPTIONS, YAMLException, EVENT_ID, SCALAR_STYLE, COLLECTION_STYLE, CHOMPING_MODE, NO_RANGE$3 = -1, simpleEscapeCheck, simpleEscapeMap, DEFAULT_TAG_HANDLERS, NO_RANGE$2 = -1, MERGE_TAG_NAME = "tag:yaml.org,2002:merge", DEFAULT_CONSTRUCTOR_OPTIONS, NO_RANGE$1 = -1, HAS_OWN, CONTEXT_FLOW_IN = 1, CONTEXT_FLOW_OUT = 2, CONTEXT_BLOCK_IN = 3, CONTEXT_BLOCK_OUT = 4, PATTERN_NON_PRINTABLE, PATTERN_FLOW_INDICATORS, PATTERN_TAG_HANDLE, NS_URI_CHAR, NS_TAG_CHAR, PATTERN_TAG_URI, PATTERN_TAG_SUFFIX, PATTERN_TAG_PREFIX, DEFAULT_PARSER_OPTIONS, DEFAULT_LOAD_OPTIONS, INVALID, VISIT_BREAK, VISIT_SKIP, ESCAPE_SEQUENCES, DEFAULT_PRESENTER_OPTIONS, DEFAULT_DUMP_OPTIONS, EVENT_DOCUMENT, EVENT_SEQUENCE, EVENT_MAPPING, EVENT_SCALAR, EVENT_ALIAS, EVENT_POP, SCALAR_STYLE_PLAIN, SCALAR_STYLE_SINGLE_QUOTED, SCALAR_STYLE_DOUBLE_QUOTED, SCALAR_STYLE_LITERAL_BLOCK, SCALAR_STYLE_FOLDED_BLOCK, COLLECTION_STYLE_BLOCK, COLLECTION_STYLE_FLOW, CHOMPING_CLIP, CHOMPING_STRIP, CHOMPING_KEEP;
+}, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, YAML11_SCHEMA, DUMP_SCHEMA, realMapTag, legacyMapTag, DEFAULT_SNIPPET_OPTIONS, YAMLException, EVENT_ID, SCALAR_STYLE, COLLECTION_STYLE, CHOMPING_MODE, NO_RANGE$3 = -1, simpleEscapeCheck, simpleEscapeMap, DEFAULT_TAG_HANDLERS, NO_RANGE$2 = -1, MERGE_TAG_NAME = "tag:yaml.org,2002:merge", DEFAULT_CONSTRUCTOR_OPTIONS, NO_RANGE$1 = -1, HAS_OWN, CONTEXT_FLOW_IN = 1, CONTEXT_FLOW_OUT = 2, CONTEXT_BLOCK_IN = 3, CONTEXT_BLOCK_OUT = 4, PATTERN_NON_PRINTABLE, PATTERN_FLOW_INDICATORS, PATTERN_TAG_HANDLE, NS_URI_CHAR, NS_TAG_CHAR, PATTERN_TAG_URI, PATTERN_TAG_SUFFIX, PATTERN_TAG_PREFIX, DEFAULT_PARSER_OPTIONS, DEFAULT_LOAD_OPTIONS, INVALID, VISIT_BREAK, VISIT_SKIP, DEFAULT_SCALAR_STYLE_RULES, SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]", SRC_B_CHAR = "[\\n\\r]", SRC_C_BYTE_ORDER_MARK = "\\uFEFF", SRC_S_WHITE = "[ \\t]", SRC_NB_CHAR, SRC_NS_CHAR, SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]", SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]", SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]", SRC_NS_PLAIN_SAFE_FLOW_OUT, SRC_NS_PLAIN_SAFE_FLOW_IN, SRC_NS_PLAIN_FIRST_FLOW_OUT, SRC_NS_PLAIN_FIRST_FLOW_IN, SRC_NS_PLAIN_CHAR_FLOW_OUT, SRC_NS_PLAIN_CHAR_FLOW_IN, SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT, SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN, SRC_NS_PLAIN_ONE_LINE_FLOW_OUT, SRC_NS_PLAIN_ONE_LINE_FLOW_IN, SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY, SRC_NS_PLAIN_ONE_LINE_FLOW_KEY, SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT, SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN, SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT, SRC_NS_PLAIN_MULTI_LINE_FLOW_IN, NS_PLAIN_FLOW_OUT, NS_PLAIN_FLOW_IN, NS_PLAIN_BLOCK_KEY, NS_PLAIN_FLOW_KEY, NB_SINGLE_ONE_LINE, NB_SINGLE_MULTI_LINE, BLOCK_SCALAR_CONTENT, DEFAULT_PRESENTER_OPTIONS, DEFAULT_DUMP_OPTIONS, EVENT_DOCUMENT, EVENT_SEQUENCE, EVENT_MAPPING, EVENT_SCALAR, EVENT_ALIAS, EVENT_POP, SCALAR_STYLE_PLAIN, SCALAR_STYLE_SINGLE_QUOTED, SCALAR_STYLE_DOUBLE_QUOTED, SCALAR_STYLE_LITERAL_BLOCK, SCALAR_STYLE_FOLDED_BLOCK, COLLECTION_STYLE_BLOCK, COLLECTION_STYLE_FLOW, CHOMPING_CLIP, CHOMPING_STRIP, CHOMPING_KEEP;
var init_js_yaml = __esm(() => {
- /*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT */
+ /*! js-yaml 5.4.2 https://github.com/nodeca/js-yaml @license MIT */
NOT_RESOLVED = Symbol("NOT_RESOLVED");
strTag = defineScalarTag("tag:yaml.org,2002:str", {
resolve: (source) => source,
@@ -3041,27 +3150,44 @@ var init_js_yaml = __esm(() => {
INVALID = Symbol("INVALID");
VISIT_BREAK = Symbol("visit:break");
VISIT_SKIP = Symbol("visit:skip");
- ESCAPE_SEQUENCES = {};
- ESCAPE_SEQUENCES[0] = "\\0";
- ESCAPE_SEQUENCES[7] = "\\a";
- ESCAPE_SEQUENCES[8] = "\\b";
- ESCAPE_SEQUENCES[9] = "\\t";
- ESCAPE_SEQUENCES[10] = "\\n";
- ESCAPE_SEQUENCES[11] = "\\v";
- ESCAPE_SEQUENCES[12] = "\\f";
- ESCAPE_SEQUENCES[13] = "\\r";
- ESCAPE_SEQUENCES[27] = "\\e";
- ESCAPE_SEQUENCES[34] = "\\\"";
- ESCAPE_SEQUENCES[92] = "\\\\";
- ESCAPE_SEQUENCES[133] = "\\N";
- ESCAPE_SEQUENCES[160] = "\\_";
- ESCAPE_SEQUENCES[8232] = "\\L";
- ESCAPE_SEQUENCES[8233] = "\\P";
+ DEFAULT_SCALAR_STYLE_RULES = {
+ applyQuoteFlowKeysOption,
+ doubleQuoteForInvisibles,
+ doubleQuoteWhitespaceOnly,
+ applyForceQuotesOption,
+ tryLongOrMultilineAsBlock,
+ quoteInvalidPlain,
+ fallbackToDoubleQuoted
+ };
+ SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
+ SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
+ SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
+ SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
+ SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
+ SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
+ SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
+ SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
+ SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
+ SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
+ SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
+ SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
+ SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
+ SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
+ SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
+ SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
+ SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
+ SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
+ NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
+ NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
+ NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
+ NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
+ NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
+ NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
+ BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
DEFAULT_PRESENTER_OPTIONS = {
indent: 2,
seqNoIndent: false,
seqInlineFirst: true,
- sortKeys: false,
lineWidth: 80,
flowBracketPadding: false,
flowSkipCommaSpace: false,
@@ -3069,6 +3195,7 @@ var init_js_yaml = __esm(() => {
quoteFlowKeys: false,
quoteStyle: "single",
forceQuotes: false,
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
tagBeforeAnchor: false
};
DEFAULT_DUMP_OPTIONS = {
@@ -3077,6 +3204,7 @@ var init_js_yaml = __esm(() => {
skipInvalid: false,
noRefs: false,
flowLevel: -1,
+ sortKeys: false,
transform: () => {}
};
EVENT_DOCUMENT = EVENT_ID.DOCUMENT;
@@ -64670,10 +64798,10 @@ var init_tmux = __esm(() => {
init_runner2();
init_tmux_utils2();
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/types.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/types.gen.js
var init_types_gen = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/serverSentEvents.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/serverSentEvents.gen.js
var createSseClient = ({ onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
let lastEventId;
const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
@@ -64782,7 +64910,7 @@ var createSseClient = ({ onSseError, onSseEvent, responseTransformer, responseVa
return { stream };
};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/auth.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/auth.gen.js
var getAuthToken = async (auth, callback) => {
const token = typeof callback === "function" ? await callback(auth) : callback;
if (!token) {
@@ -64797,7 +64925,7 @@ var getAuthToken = async (auth, callback) => {
return token;
};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/bodySerializer.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/bodySerializer.gen.js
var jsonBodySerializer;
var init_bodySerializer_gen = __esm(() => {
jsonBodySerializer = {
@@ -64805,7 +64933,7 @@ var init_bodySerializer_gen = __esm(() => {
};
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/pathSerializer.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/pathSerializer.gen.js
var separatorArrayExplode = (style) => {
switch (style) {
case "label":
@@ -64903,7 +65031,7 @@ var separatorArrayExplode = (style) => {
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/utils.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/utils.gen.js
var PATH_PARAM_RE, defaultPathSerializer = ({ path, url: _url }) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
@@ -64972,7 +65100,7 @@ var init_utils_gen = __esm(() => {
PATH_PARAM_RE = /\{[^{}]+\}/g;
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/utils.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/utils.gen.js
class Interceptors {
_fns;
constructor() {
@@ -65175,7 +65303,7 @@ var init_utils_gen2 = __esm(() => {
};
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/client.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/client.gen.js
var createClient = (config = {}) => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = () => ({ ..._config });
@@ -65326,7 +65454,7 @@ var init_client_gen = __esm(() => {
init_utils_gen2();
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/params.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/core/params.gen.js
var extraPrefixesMap, extraPrefixes;
var init_params_gen = __esm(() => {
extraPrefixesMap = {
@@ -65338,7 +65466,7 @@ var init_params_gen = __esm(() => {
extraPrefixes = Object.entries(extraPrefixesMap);
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/index.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client/index.js
var init_client = __esm(() => {
init_bodySerializer_gen();
init_params_gen();
@@ -65346,7 +65474,7 @@ var init_client = __esm(() => {
init_utils_gen2();
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/client.gen.js
var client;
var init_client_gen2 = __esm(() => {
init_client();
@@ -65355,7 +65483,7 @@ var init_client_gen2 = __esm(() => {
}));
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/sdk.gen.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/gen/sdk.gen.js
class _HeyApiClient {
_client = client;
constructor(args) {
@@ -66006,7 +66134,7 @@ var init_sdk_gen = __esm(() => {
};
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/error-interceptor.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/error-interceptor.js
function wrapClientError(error, response, request, opts) {
if (!opts?.throwOnError)
return error;
@@ -66033,7 +66161,7 @@ function describe(request, response) {
return `${method} ${url}${status ? " \u2192 " + status : ""}${statusText ? " " + statusText : ""}`;
}
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/client.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/client.js
function pick2(value, fallback) {
if (!value)
return;
@@ -66543,7 +66671,7 @@ var require_cross_spawn = __commonJS(function(exports, module) {
module.exports._enoent = enoent;
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/process.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/process.js
import { spawnSync as spawnSync2 } from "child_process";
function stop(proc) {
if (proc.exitCode !== null || proc.signalCode !== null)
@@ -66577,7 +66705,7 @@ function bindAbort(proc, signal, onAbort) {
}
var init_process = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/server.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/server.js
async function createOpencodeServer(options) {
options = Object.assign({
hostname: "127.0.0.1",
@@ -66660,7 +66788,7 @@ var init_server = __esm(() => {
import_cross_spawn = __toESM(require_cross_spawn(), 1);
});
-// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/index.js
+// node_modules/.bun/@[email protected]/node_modules/@opencode-ai/sdk/dist/index.js
async function createOpencode(options) {
const server2 = await createOpencodeServer({
...options
@@ -67524,83 +67652,7 @@ var init_shared = __esm(() => {
init_replace_tool_args();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/core.js
-function $constructor(name, initializer, params) {
- function init(inst, def) {
- if (!inst._zod) {
- Object.defineProperty(inst, "_zod", {
- value: {
- def,
- constr: _,
- traits: new Set
- },
- enumerable: false
- });
- }
- if (inst._zod.traits.has(name)) {
- return;
- }
- inst._zod.traits.add(name);
- initializer(inst, def);
- const proto = _.prototype;
- const keys = Object.keys(proto);
- for (let i = 0;i < keys.length; i++) {
- const k = keys[i];
- if (!(k in inst)) {
- inst[k] = proto[k].bind(inst);
- }
- }
- }
- const Parent = params?.Parent ?? Object;
-
- class Definition extends Parent {
- }
- Object.defineProperty(Definition, "name", { value: name });
- function _(def) {
- var _a;
- const inst = params?.Parent ? new Definition : this;
- init(inst, def);
- (_a = inst._zod).deferred ?? (_a.deferred = []);
- for (const fn of inst._zod.deferred) {
- fn();
- }
- return inst;
- }
- Object.defineProperty(_, "init", { value: init });
- Object.defineProperty(_, Symbol.hasInstance, {
- value: (inst) => {
- if (params?.Parent && inst instanceof params.Parent)
- return true;
- return inst?._zod?.traits?.has(name);
- }
- });
- Object.defineProperty(_, "name", { value: name });
- return _;
-}
-function config(newConfig) {
- if (newConfig)
- Object.assign(globalConfig, newConfig);
- return globalConfig;
-}
-var _a, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig;
-var init_core = __esm(() => {
- $brand = Symbol("zod_brand");
- $ZodAsyncError = class $ZodAsyncError extends Error {
- constructor() {
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
- }
- };
- $ZodEncodeError = class $ZodEncodeError extends Error {
- constructor(name) {
- super(`Encountered unidirectional transform during encode: ${name}`);
- this.name = "ZodEncodeError";
- }
- };
- (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
- globalConfig = globalThis.__zod_globalConfig;
-});
-
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/util.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
@@ -67614,18 +67666,23 @@ function jsonStringifyReplacer(_, value) {
return value.toString();
return value;
}
-function cached(getter) {
- const set = false;
- return {
- get value() {
- if (!set) {
- const value = getter();
- Object.defineProperty(this, "value", { value });
- return value;
- }
- throw new Error("cached value already set");
+
+class Cached {
+ constructor(getter) {
+ this._getter = getter;
+ this._value = undefined;
+ }
+ get value() {
+ const getter = this._getter;
+ if (getter !== undefined) {
+ this._value = getter();
+ this._getter = undefined;
}
- };
+ return this._value;
+ }
+}
+function cached(getter) {
+ return new Cached(getter);
}
function nullish(input) {
return input === null || input === undefined;
@@ -67638,32 +67695,11 @@ function cleanRegex(source) {
function floatSafeRemainder(val, step) {
const ratio = val / step;
const roundedRatio = Math.round(ratio);
- const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance)
return 0;
return ratio - roundedRatio;
}
-function defineLazy(object, key, getter) {
- let value = undefined;
- Object.defineProperty(object, key, {
- get() {
- if (value === EVALUATING) {
- return;
- }
- if (value === undefined) {
- value = EVALUATING;
- value = getter();
- }
- return value;
- },
- set(v) {
- Object.defineProperty(object, key, {
- value: v
- });
- },
- configurable: true
- });
-}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
@@ -67672,6 +67708,56 @@ function assignProp(target, prop, value) {
configurable: true
});
}
+function rawShape(def) {
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
+ return desc?.get ? desc.get.raw : desc?.value;
+}
+function sourceShape(schema) {
+ return rawShape(schema._zod.def) ?? schema._zod.def.shape;
+}
+function deferProp(target, key, getter) {
+ Object.defineProperty(target, key, {
+ get() {
+ const value = getter();
+ assignProp(this, key, value);
+ return value;
+ },
+ enumerable: true,
+ configurable: true
+ });
+}
+function putProp(target, key, value) {
+ if (key in target)
+ assignProp(target, key, value);
+ else
+ target[key] = value;
+}
+function mirrorShape(target, source, keys, wrap) {
+ const raw = sourceShape(source);
+ for (const key of keys) {
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
+ if (!desc.enumerable)
+ continue;
+ if (desc.get) {
+ deferProp(target, key, () => {
+ const value = source._zod.def.shape[key];
+ return wrap ? wrap(value, key) : value;
+ });
+ } else
+ putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
+ }
+}
+function mirrorProps(target, source) {
+ for (const key of Reflect.ownKeys(source)) {
+ const desc = Object.getOwnPropertyDescriptor(source, key);
+ if (!desc.enumerable)
+ continue;
+ if (desc.get)
+ deferProp(target, key, () => source[key]);
+ else
+ putProp(target, key, desc.value);
+ }
+}
function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
@@ -67750,7 +67836,7 @@ function stringifyPrimitive(value) {
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
+ return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional";
});
}
function pick3(schema, mask) {
@@ -67760,23 +67846,21 @@ function pick3(schema, mask) {
if (hasChecks) {
throw new Error(".pick() cannot be used on object schemas containing refinements");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const newShape = {};
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- newShape[key] = currDef.shape[key];
- }
- assignProp(this, "shape", newShape);
- return newShape;
- },
- checks: []
- });
- return clone(schema, def);
+ const newShape = {};
+ mirrorShape(newShape, schema, maskedKeys(schema, mask));
+ return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
+}
+function maskedKeys(schema, mask) {
+ const raw = sourceShape(schema);
+ const keys = [];
+ for (const key of Reflect.ownKeys(mask)) {
+ if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {
+ throw new Error(`Unrecognized key: "${String(key)}"`);
+ }
+ if (mask[key])
+ keys.push(key);
+ }
+ return keys;
}
function omit(schema, mask) {
const currDef = schema._zod.def;
@@ -67785,23 +67869,10 @@ function omit(schema, mask) {
if (hasChecks) {
throw new Error(".omit() cannot be used on object schemas containing refinements");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const newShape = { ...schema._zod.def.shape };
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- delete newShape[key];
- }
- assignProp(this, "shape", newShape);
- return newShape;
- },
- checks: []
- });
- return clone(schema, def);
+ const omitted = new Set(maskedKeys(schema, mask));
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));
+ return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
}
function extend(schema, shape) {
if (!isPlainObject3(shape)) {
@@ -67810,45 +67881,39 @@ function extend(schema, shape) {
const checks = schema._zod.def.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
- const existingShape = schema._zod.def.shape;
- for (const key in shape) {
+ const existingShape = sourceShape(schema);
+ for (const key of Reflect.ownKeys(shape)) {
if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
}
}
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- }
- });
- return clone(schema, def);
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
+}
+function extended(schema, shape) {
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
+ mirrorProps(newShape, shape);
+ return newShape;
}
function safeExtend(schema, shape) {
if (!isPlainObject3(shape)) {
throw new Error("Invalid input to safeExtend: expected a plain object");
}
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- }
- });
- return clone(schema, def);
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
}
function merge(a, b) {
+ if (!b?._zod?.def) {
+ throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
+ }
if (a._zod.def.checks?.length) {
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
}
+ const newShape = {};
+ mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));
+ mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));
const def = mergeDefs(a._zod.def, {
- get shape() {
- const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
- assignProp(this, "shape", _shape);
- return _shape;
- },
+ shape: newShape,
get catchall() {
return b._zod.def.catchall;
},
@@ -67856,74 +67921,23 @@ function merge(a, b) {
});
return clone(a, def);
}
-function partial(Class, schema, mask) {
+function partial(Class, schema, mask, name = "partial") {
const currDef = schema._zod.def;
const checks = currDef.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
- throw new Error(".partial() cannot be used on object schemas containing refinements");
- }
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in oldShape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- } else {
- for (const key in oldShape) {
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- }
- assignProp(this, "shape", shape);
- return shape;
- },
- checks: []
- });
- return clone(schema, def);
+ throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
+ }
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && ((value, key) => selected && !selected.has(key) ? value : new Class({ type: "optional", innerType: value })));
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));
}
function required(Class, schema, mask) {
- const def = mergeDefs(schema._zod.def, {
- get shape() {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- } else {
- for (const key in oldShape) {
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- }
- assignProp(this, "shape", shape);
- return shape;
- }
- });
- return clone(schema, def);
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;
+ const newShape = {};
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => selected && !selected.has(key) ? value : new Class({ type: "nonoptional", innerType: value }));
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));
}
function aborted(x, startIndex = 0) {
if (x.aborted === true)
@@ -67956,15 +67970,48 @@ function prefixIssues(path, issues) {
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
+function attachSchema(issues, start, inst) {
+ var _a;
+ for (let i = start;i < issues.length; i++) {
+ (_a = issues[i]).schema ?? (_a.schema = inst);
+ }
+}
function finalizeIssue(iss, ctx, config) {
- const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
- const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
- rest.path ?? (rest.path = []);
- rest.message = message;
+ var _a;
+ const traits = iss.inst?._zod?.traits;
+ if (traits?.has("$ZodType")) {
+ if (traits.has("$ZodCheck"))
+ (_a = iss).schema ?? (_a.schema = iss.inst);
+ else
+ iss.schema = iss.inst;
+ }
+ const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
+ const full = {};
+ for (const k of Object.keys(iss)) {
+ if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__")
+ continue;
+ full[k] = iss[k];
+ }
+ full.path ?? (full.path = []);
+ full.message = message;
if (ctx?.reportInput) {
- rest.input = _input;
+ full.input = iss.input;
}
- return rest;
+ return full;
+}
+function codePointLength(str) {
+ const units = str.length;
+ if (!highSurrogate.test(str))
+ return units;
+ let count = units;
+ for (let i = 0;i < units - 1; i++) {
+ if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
+ count--;
+ i++;
+ }
+ }
+ return count;
}
function getLengthableOrigin(input) {
if (Array.isArray(input))
@@ -68006,10 +68053,111 @@ function issue(...args) {
}
return { ...iss };
}
-var EVALUATING, captureStackTrace, allowsEval, propertyKeyTypes, NUMBER_FORMAT_RANGES;
+function members(proto, table) {
+ for (const key in table) {
+ const desc = Object.getOwnPropertyDescriptor(table, key);
+ if (desc.get)
+ Object.defineProperty(proto, key, { ...desc, enumerable: false });
+ else
+ defineBound(proto, key, desc.value);
+ }
+}
+function own(inst, key, value, enumerable = true) {
+ Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });
+ return value;
+}
+function hide(inst, key, value) {
+ return own(inst, key, value, false);
+}
+function derived(computes, table) {
+ for (const key in computes) {
+ const compute = computes[key];
+ Object.defineProperty(table, key, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ return own(this, key, compute(this));
+ },
+ set(value) {
+ own(this, key, value);
+ }
+ });
+ }
+ return table;
+}
+function defineBound(proto, key, fn) {
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ return this == null ? fn : own(this, key, fn.bind(this));
+ },
+ set(value) {
+ own(this, key, value);
+ }
+ });
+}
+function claim(inst, sentinel) {
+ const proto = Object.getPrototypeOf(inst);
+ return sentinel in proto ? undefined : proto;
+}
+function defineLazyInternal(inst, key, compute) {
+ const proto = Object.getPrototypeOf(inst._zod);
+ if (key in proto && installing !== inst._zod) {
+ installing = undefined;
+ return;
+ }
+ installing = inst._zod;
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ Object.defineProperty(this, key, breaker);
+ const outer = broke;
+ broke = false;
+ try {
+ const value = compute(this);
+ if (broke)
+ delete this[key];
+ else
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
+ broke = broke || outer;
+ return value;
+ } catch (err) {
+ delete this[key];
+ broke = broke || outer;
+ throw err;
+ }
+ },
+ set(value) {
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
+ }
+ });
+}
+function installLazyProp(inst, key, make, enumerable) {
+ const proto = claim(inst, key);
+ if (!proto)
+ return;
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get() {
+ const desc = { configurable: true, writable: true, enumerable, value: undefined };
+ Object.defineProperty(this, key, desc);
+ desc.value = make(this);
+ Object.defineProperty(this, key, desc);
+ return desc.value;
+ },
+ set(value) {
+ Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });
+ }
+ });
+}
+function constantCatch(value) {
+ const fn = () => value;
+ fn[CONSTANT_CATCH] = true;
+ return fn;
+}
+var captureStackTrace, allowsEval, propertyKeyTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, highSurrogate, installing, broke = false, breaker, CONSTANT_CATCH = "~constantCatch";
var init_util = __esm(() => {
init_core();
- EVALUATING = /* @__PURE__ */ Symbol("evaluating");
captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
allowsEval = /* @__PURE__ */ cached(() => {
if (globalConfig.jitless) {
@@ -68027,23 +68175,173 @@ var init_util = __esm(() => {
}
});
propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
- NUMBER_FORMAT_RANGES = {
+ NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
+ }))();
+ BIGINT_FORMAT_RANGES = {
+ int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
+ uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
+ };
+ highSurrogate = /[\uD800-\uDBFF]/;
+ breaker = {
+ configurable: true,
+ get() {
+ broke = true;
+ return;
+ }
};
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/errors.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/core.js
+function newError(Definition) {
+ const E = _E;
+ if (E) {
+ const saved = E.stackTraceLimit;
+ if (typeof saved === "number") {
+ try {
+ E.stackTraceLimit = 0;
+ } catch {
+ _E = null;
+ return new Definition;
+ }
+ try {
+ return new Definition;
+ } finally {
+ E.stackTraceLimit = saved;
+ }
+ }
+ }
+ return new Definition;
+}
+function $constructor(name, initializer, proto, params) {
+ const zodProto = {};
+ function Internals(def) {
+ this.def = def;
+ this.constr = _;
+ this.traits = new Set;
+ }
+ Internals.prototype = zodProto;
+ const protoMembers = proto;
+ const initialized = protoMembers && new WeakSet;
+ function init(inst, def) {
+ if (!inst._zod) {
+ _zodDesc.value = new Internals(def);
+ try {
+ Object.defineProperty(inst, "_zod", _zodDesc);
+ } finally {
+ _zodDesc.value = undefined;
+ }
+ } else if (inst._zod.traits.has(name)) {
+ return;
+ }
+ inst._zod.traits.add(name);
+ initializer(inst, def);
+ if (initialized) {
+ const own = Object.getPrototypeOf(inst);
+ const ctorProto = inst._zod.constr.prototype;
+ let up = own;
+ while (up && up !== ctorProto)
+ up = Object.getPrototypeOf(up);
+ const target = up ?? own;
+ if (!initialized.has(target)) {
+ initialized.add(target);
+ members(target, protoMembers);
+ }
+ }
+ const proto = _.prototype;
+ for (const k in proto) {
+ if (!Object.prototype.hasOwnProperty.call(proto, k))
+ continue;
+ if (!(k in inst)) {
+ inst[k] = proto[k].bind(inst);
+ }
+ }
+ }
+ const Parent = params?.Parent ?? Object;
+
+ class Definition extends Parent {
+ }
+ Object.defineProperty(Definition, "name", { value: name });
+ function _(def) {
+ const inst = params?.Parent ? newError(Definition) : this;
+ init(inst, def);
+ const deferred = inst._zod.deferred;
+ if (deferred) {
+ for (const fn of deferred) {
+ fn();
+ }
+ inst._zod.deferred = undefined;
+ }
+ const pp = globalThis.__zod_globalConfig?.postProcessor;
+ if (pp)
+ pp(inst);
+ return inst;
+ }
+ Object.defineProperty(_, "init", { value: init });
+ Object.defineProperty(_, Symbol.hasInstance, {
+ value: (inst) => {
+ if (params?.Parent && inst instanceof params.Parent)
+ return true;
+ return inst?._zod?.traits?.has(name);
+ }
+ });
+ Object.defineProperty(_, "name", { value: name });
+ return _;
+}
+function config(newConfig) {
+ if (newConfig)
+ Object.assign(globalConfig, newConfig);
+ return globalConfig;
+}
+var _a, _zodDesc, _E, $ZodAsyncError, $ZodEncodeError, globalConfig;
+var init_core = __esm(() => {
+ init_util();
+ _zodDesc = { value: undefined, enumerable: false };
+ _E = "captureStackTrace" in Error ? Error : null;
+ $ZodAsyncError = class $ZodAsyncError extends Error {
+ constructor() {
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
+ }
+ };
+ $ZodEncodeError = class $ZodEncodeError extends Error {
+ constructor(name) {
+ super(`Encountered unidirectional transform during encode: ${name}`);
+ this.name = "ZodEncodeError";
+ }
+ };
+ (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
+ globalConfig = globalThis.__zod_globalConfig;
+});
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/errors.js
+function _getMessage() {
+ const internals = this._zod;
+ internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
+ return internals.message;
+}
+function _setMessage(value) {
+ this._zod.message = value;
+}
+function node(obj, key, make) {
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) {
+ if (key === "__proto__") {
+ Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
+ } else {
+ obj[key] = make();
+ }
+ }
+ return obj[key];
+}
function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) {
if (sub.path.length > 0) {
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
- fieldErrors[sub.path[0]].push(mapper(sub));
+ node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
@@ -68070,13 +68368,25 @@ function formatError2(error, mapper = (issue) => issue.message) {
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- } else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue));
+ if (el === "_errors") {
+ if (terminal)
+ curr._errors.push(mapper(issue));
+ i++;
+ continue;
+ }
+ if (!Object.prototype.hasOwnProperty.call(curr, el)) {
+ Object.defineProperty(curr, el, {
+ value: { _errors: [] },
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ const node = curr[el];
+ if (terminal) {
+ node._errors.push(mapper(issue));
}
- curr = curr[el];
+ curr = node;
i++;
}
}
@@ -68086,82 +68396,167 @@ function formatError2(error, mapper = (issue) => issue.message) {
processError(error);
return fieldErrors;
}
-var initializer = (inst, def) => {
+var _messageDesc, _issuesDesc, _installedToString, initializer = (inst, def) => {
inst.name = "$ZodError";
- Object.defineProperty(inst, "_zod", {
- value: inst._zod,
- enumerable: false
- });
- Object.defineProperty(inst, "issues", {
- value: def,
- enumerable: false
- });
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
- Object.defineProperty(inst, "toString", {
- value: () => inst.message,
- enumerable: false
- });
+ _issuesDesc.value = def;
+ Object.defineProperty(inst, "issues", _issuesDesc);
+ _issuesDesc.value = undefined;
+ Object.defineProperty(inst, "message", _messageDesc);
+ const proto = Object.getPrototypeOf(inst);
+ if (!_installedToString.has(proto)) {
+ _installedToString.add(proto);
+ Object.defineProperty(proto, "toString", {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const value = () => this.message;
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
+ return value;
+ },
+ set(value) {
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
+ }
+ });
+ }
}, $ZodError, $ZodRealError;
var init_errors = __esm(() => {
init_core();
init_util();
+ _messageDesc = {
+ get: _getMessage,
+ set: _setMessage,
+ enumerable: true,
+ configurable: true
+ };
+ _issuesDesc = { value: undefined, enumerable: false };
+ _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
$ZodError = $constructor("$ZodError", initializer);
- $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
+ $ZodRealError = $constructor("$ZodError", initializer, undefined, {
+ Parent: Error
+ });
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/parse.js
-var _parse = (_Err) => (schema, value, _ctx, _params) => {
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
- const result = schema._zod.run({ value, issues: [] }, ctx);
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/parse.js
+function finalizeParams(callee, params) {
+ return { callee: params?.callee ?? callee, Err: params?.Err };
+}
+function failure(Err, issues, ctx) {
+ let error;
+ return {
+ success: false,
+ get error() {
+ if (!error) {
+ error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ issues = undefined;
+ ctx = undefined;
+ }
+ return error;
+ },
+ set error(e) {
+ error = e;
+ issues = undefined;
+ ctx = undefined;
+ }
+ };
+}
+function validateFallback(schema, value, _ctx) {
+ const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true };
+ const fallbackRun = schema._zod.bag.fallbackRun;
+ let result;
+ if (fallbackRun) {
+ ctx[COMPILE_FALLBACK] = true;
+ result = fallbackRun({ value, issues: [] }, ctx);
+ } else {
+ result = schema._zod.run({ value, issues: [] }, ctx);
+ }
if (result instanceof Promise) {
throw new $ZodAsyncError;
}
- if (result.issues.length) {
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, _params?.callee);
- throw e;
- }
- return result.value;
-}, _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
- const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
- let result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise)
- result = await result;
- if (result.issues.length) {
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, params?.callee);
- throw e;
- }
- return result.value;
+ return result.issues.length === 0;
+}
+var _parse = (_Err) => {
+ const fn = (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
+ const result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ throw new $ZodAsyncError;
+ }
+ if (result.issues.length) {
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, _params?.callee ?? fn);
+ throw e;
+ }
+ return result.value;
+ };
+ return fn;
+}, _parseAsync = (_Err) => {
+ const fn = async (schema, value, _ctx, params) => {
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ if (result.issues.length) {
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, params?.callee ?? fn);
+ throw e;
+ }
+ return result.value;
+ };
+ return fn;
}, _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new $ZodAsyncError;
}
- return result.issues.length ? {
- success: false,
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
-}, safeParse, _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
+ return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
+}, _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
- return result.issues.length ? {
- success: false,
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
-}, safeParseAsync, _encode = (_Err) => (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
- return _parse(_Err)(schema, value, ctx);
-}, _decode = (_Err) => (schema, value, _ctx) => {
- return _parse(_Err)(schema, value, _ctx);
-}, _encodeAsync = (_Err) => async (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
- return _parseAsync(_Err)(schema, value, ctx);
-}, _decodeAsync = (_Err) => async (schema, value, _ctx) => {
- return _parseAsync(_Err)(schema, value, _ctx);
+ return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
+}, COMPILE_INVALID, COMPILE_FALLBACK, validate = (schema, value, _ctx) => {
+ const validator = schema._zod.bag.validator;
+ if (validator !== undefined) {
+ if (validator(value) !== COMPILE_INVALID)
+ return true;
+ if (validator.definite === true && _ctx === undefined)
+ return false;
+ }
+ return validateFallback(schema, value, _ctx);
+}, validateAsync = async (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ return result.issues.length === 0;
+}, _encode = (_Err) => {
+ const parse = _parse(_Err);
+ const fn = (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return parse(schema, value, ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+}, _decode = (_Err) => {
+ const parse = _parse(_Err);
+ const fn = (schema, value, _ctx, _params) => {
+ return parse(schema, value, _ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+}, _encodeAsync = (_Err) => {
+ const parseAsync = _parseAsync(_Err);
+ const fn = async (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return await parseAsync(schema, value, ctx, finalizeParams(fn, _params));
+ };
+ return fn;
+}, _decodeAsync = (_Err) => {
+ const parseAsync = _parseAsync(_Err);
+ const fn = async (schema, value, _ctx, _params) => {
+ return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
+ };
+ return fn;
}, _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _safeParse(_Err)(schema, value, ctx);
@@ -68175,61 +68570,62 @@ var _parse = (_Err) => (schema, value, _ctx, _params) => {
};
var init_parse = __esm(() => {
init_core();
- init_errors();
init_util();
- safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
- safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
+ COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
+ COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/regexes.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/regexes.js
+function nanoidOfLength(length) {
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
+}
function emoji() {
return new RegExp(_emoji, "u");
}
+function anchor(source) {
+ return new RegExp(`^${source}$`);
+}
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
- const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
+ const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
return regex;
}
function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
- const time = timeSource({ precision: args.precision });
const opts = ["Z"];
- if (args.local)
- opts.push("");
if (args.offset)
opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
- const timeRegex = `${time}(?:${opts.join("|")})`;
+ const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid = (version) => {
if (!version)
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)$/;
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})$`);
-}, email, _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, 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])))`, date, string = (params) => {
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
- return new RegExp(`^${regex}$`);
-}, integer, number, boolean, lowercase, uppercase;
+}, email, _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, 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])))`, date, anyString, integer, number, boolean, lowercase, uppercase;
var init_regexes = __esm(() => {
cuid = /^[cC][0-9a-z]{6,}$/;
cuid2 = /^[0-9a-z]+$/;
- ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
+ ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
xid = /^[0-9a-vA-V]{20}$/;
ksuid = /^[A-Za-z0-9]{27}$/;
nanoid = /^[a-zA-Z0-9_-]{21}$/;
duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
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})$/;
- email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
+ email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
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])$/;
ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
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])$/;
- 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])$/;
+ cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
- base64url = /^[A-Za-z0-9_-]*$/;
+ base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
httpProtocol = /^https?$/;
e164 = /^\+[1-9]\d{6,14}$/;
- date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
+ date = /* @__PURE__ */ anchor(dateSource);
+ anyString = /^[\s\S]{0,}$/;
integer = /^-?\d+$/;
number = /^-?\d+(?:\.\d+)?$/;
boolean = /^(?:true|false)$/i;
@@ -68237,8 +68633,11 @@ var init_regexes = __esm(() => {
uppercase = /^[^a-z]*$/;
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/checks.js
-var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite;
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/checks.js
+var $ZodCheck, _whenHasLength = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.length !== undefined;
+}, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite;
var init_checks = __esm(() => {
init_core();
init_regexes();
@@ -68257,22 +68656,12 @@ var init_checks = __esm(() => {
$ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
- if (def.value < curr) {
- if (def.inclusive)
- bag.maximum = def.value;
- else
- bag.exclusiveMaximum = def.value;
- }
- });
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
- origin,
+ origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
@@ -68285,22 +68674,12 @@ var init_checks = __esm(() => {
$ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
- if (def.value > curr) {
- if (def.inclusive)
- bag.minimum = def.value;
- else
- bag.exclusiveMinimum = def.value;
- }
- });
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
- origin,
+ origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
@@ -68312,14 +68691,10 @@ var init_checks = __esm(() => {
});
$ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
- inst._zod.onattach.push((inst) => {
- var _a;
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
- });
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
- const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
+ const isMultiple = typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
@@ -68338,14 +68713,6 @@ var init_checks = __esm(() => {
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.format = def.format;
- bag.minimum = minimum;
- bag.maximum = maximum;
- if (isInt)
- bag.pattern = integer;
- });
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
@@ -68414,18 +68781,11 @@ var init_checks = __esm(() => {
$ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
- if (def.maximum < curr)
- inst._zod.bag.maximum = def.maximum;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units;
if (length <= def.maximum)
return;
const origin = getLengthableOrigin(input);
@@ -68443,18 +68803,11 @@ var init_checks = __esm(() => {
$ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
- if (def.minimum > curr)
- inst._zod.bag.minimum = def.minimum;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units;
if (length >= def.minimum)
return;
const origin = getLengthableOrigin(input);
@@ -68472,19 +68825,11 @@ var init_checks = __esm(() => {
$ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.minimum = def.length;
- bag.maximum = def.length;
- bag.length = def.length;
- });
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
- const length = input.length;
+ const units = input.length;
+ const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
if (length === def.length)
return;
const origin = getLengthableOrigin(input);
@@ -68503,14 +68848,6 @@ var init_checks = __esm(() => {
$ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.format = def.format;
- if (def.pattern) {
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(def.pattern);
- }
- });
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
@@ -68557,13 +68894,8 @@ var init_checks = __esm(() => {
$ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = escapeRegex(def.includes);
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
@@ -68582,11 +68914,6 @@ var init_checks = __esm(() => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
@@ -68605,11 +68932,6 @@ var init_checks = __esm(() => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
- inst._zod.onattach.push((inst) => {
- const bag = inst._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
@@ -68632,18 +68954,21 @@ var init_checks = __esm(() => {
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/doc.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/doc.js
class Doc {
- constructor(args = []) {
+ constructor(args = [], closed = {}) {
this.content = [];
this.indent = 0;
- if (this)
- this.args = args;
+ this.args = args;
+ this.closed = closed;
}
indented(fn) {
this.indent += 1;
- fn(this);
- this.indent -= 1;
+ try {
+ fn(this);
+ } finally {
+ this.indent -= 1;
+ }
}
write(arg) {
if (typeof arg === "function") {
@@ -68662,25 +68987,106 @@ class Doc {
}
compile() {
const F = Function;
- const args = this?.args;
const content = this?.content ?? [``];
- const lines = [...content.map((x) => ` ${x}`)];
- return new F(...args, lines.join(`
-`));
+ const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {
+${content.join(`
+`)}
+};`);
+ return factory(...Object.values(this.closed));
}
}
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/versions.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/versions.js
var version;
var init_versions = __esm(() => {
version = {
major: 4,
- minor: 4,
- patch: 3
+ minor: 6,
+ patch: 5
};
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/schemas.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/schemas.js
+async function validateAsync2(inst, value) {
+ const ctx = { async: true };
+ return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx);
+}
+function standardProps(inst) {
+ return {
+ validate: (value) => {
+ const ctx = { async: false };
+ try {
+ const r = inst._zod.run({ value, issues: [] }, ctx);
+ if (!(r instanceof Promise))
+ return toStandardResult(r, ctx);
+ } catch (_) {}
+ return validateAsync2(inst, value);
+ },
+ vendor: "zod",
+ version: 1
+ };
+}
+function canParseURL(input) {
+ try {
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function")
+ return URL.canParse(input);
+ new URL(input);
+ return true;
+ } catch {
+ return false;
+ }
+}
+function validateURL(trimmed, def) {
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
+ return canParseURL(trimmed) || URL_UNPARSEABLE;
+ }
+ return parseURLObject(trimmed, def);
+}
+function parseURLObject(trimmed, def) {
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
+ return URL_BAD_FORMAT;
+ }
+ try {
+ if (typeof URL !== "undefined") {
+ const URLStatic = URL;
+ if (typeof URLStatic.parse === "function")
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
+ }
+ return new URL(trimmed);
+ } catch {
+ return URL_UNPARSEABLE;
+ }
+}
+function stripTabAndNewline(value) {
+ return value.replace(asciiTabOrNewline, "");
+}
+function urlHostnameOk(url, hostname) {
+ hostname.lastIndex = 0;
+ return hostname.test(url.hostname);
+}
+function urlProtocolOk(url, protocol) {
+ protocol.lastIndex = 0;
+ return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
+}
+function isValidIPv6(value) {
+ if (!ipv6Alphabet.test(value))
+ return false;
+ return canParseURL(`http://[${value}]`);
+}
+function isValidCIDRv6(value) {
+ const parts = value.split("/");
+ if (parts.length !== 2)
+ return false;
+ const [address, prefix] = parts;
+ if (!prefix)
+ return false;
+ const prefixNum = Number(prefix);
+ if (`${prefixNum}` !== prefix)
+ return false;
+ if (prefixNum < 0 || prefixNum > 128)
+ return false;
+ return isValidIPv6(address);
+}
function isValidBase64(data) {
if (data === "")
return true;
@@ -68696,7 +69102,7 @@ function isValidBase64(data) {
}
}
function isValidBase64URL(data) {
- if (!base64url.test(data))
+ if (!base64urlCharset.test(data))
return false;
const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
@@ -68728,15 +69134,19 @@ function handleArrayResult(result, final, index) {
}
final.value[index] = result.value;
}
-function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
+function handlePropertyResult(result, final, key, input, optin, optout) {
const isPresent = key in input;
+ const isOptionalOut = optout === "optional";
+ if (!isPresent && isOptionalOut && optin === "optional") {
+ return;
+ }
if (result.issues.length) {
- if (isOptionalIn && isOptionalOut && !isPresent) {
+ if (optin !== undefined && isOptionalOut && !isPresent) {
return;
}
final.issues.push(...prefixIssues(key, result.issues));
}
- if (!isPresent && !isOptionalIn) {
+ if (!isPresent && optin === undefined) {
if (!result.issues.length) {
final.issues.push({
code: "invalid_type",
@@ -68748,7 +69158,7 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona
return;
}
if (result.value === undefined) {
- if (isPresent) {
+ if (isPresent || optin === "defaulted" && !isOptionalOut) {
final.value[key] = undefined;
}
} else {
@@ -68757,41 +69167,54 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona
}
function normalizeDef(def) {
const keys = Object.keys(def.shape);
- for (const k of keys) {
+ const ownSymbols = Object.getOwnPropertySymbols(def.shape);
+ const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
+ const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
+ for (const k of allKeys) {
if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
+ throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
}
}
const okeys = optionalKeys(def.shape);
return {
...def,
- keys,
+ allKeys,
+ symbolKeys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
}
-function handleCatchall(proms, input, payload, ctx, def, inst) {
+function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {
const unrecognized = [];
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
- const isOptionalIn = _catchall.optin === "optional";
- const isOptionalOut = _catchall.optout === "optional";
+ const optin = _catchall.optin;
+ const optout = _catchall.optout;
+ let seen = 0;
for (const key in input) {
- if (key === "__proto__")
- continue;
+ if (abortEarly && payload.issues.length !== seen) {
+ if (aborted(payload, seen))
+ break;
+ seen = payload.issues.length;
+ }
if (keySet.has(key))
continue;
+ if (key === "__proto__") {
+ if (t === "never")
+ unrecognized.push(key);
+ continue;
+ }
if (t === "never") {
unrecognized.push(key);
continue;
}
const r = _catchall.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
} else {
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ handlePropertyResult(r, payload, key, input, optin, optout);
}
}
if (unrecognized.length) {
@@ -68799,7 +69222,8 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
code: "unrecognized_keys",
keys: unrecognized,
input,
- inst
+ inst,
+ continue: true
});
}
if (!proms.length)
@@ -68828,6 +69252,24 @@ function handleUnionResults(results, final, inst, ctx) {
});
return final;
}
+function discriminatorMap(def) {
+ const map = new Map;
+ for (const option of def.options) {
+ const values = option._zod.propValues?.[def.discriminator];
+ if (!values || values.size === 0)
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ for (const value of values) {
+ if (map.has(value)) {
+ if (value !== undefined)
+ throw new Error(`Duplicate discriminator value "${String(value)}"`);
+ map.set(value, null);
+ } else {
+ map.set(value, option);
+ }
+ }
+ }
+ return map;
+}
function mergeValues(a, b) {
if (a === b) {
return { valid: true, data: a };
@@ -68839,7 +69281,11 @@ function mergeValues(a, b) {
const bKeys = Object.keys(b);
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
+ if (Object.prototype.hasOwnProperty.call(newObj, "__proto__"))
+ delete newObj.__proto__;
for (const key of sharedKeys) {
+ if (key === "__proto__")
+ continue;
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return {
@@ -68875,47 +69321,57 @@ function mergeValues(a, b) {
function handleIntersectionResults(result, left, right) {
const unrecKeys = new Map;
let unrecIssue;
- for (const iss of left.issues) {
- if (iss.code === "unrecognized_keys") {
+ const keyIssues = new Map;
+ const collect = (iss, side) => {
+ let keys;
+ if (iss.code === "unrecognized_keys" && !iss.path?.length) {
unrecIssue ?? (unrecIssue = iss);
- for (const k of iss.keys) {
- if (!unrecKeys.has(k))
- unrecKeys.set(k, {});
- unrecKeys.get(k).l = true;
- }
+ keys = iss.keys;
+ } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
+ const k = String(iss.path[0]);
+ if (!keyIssues.has(k))
+ keyIssues.set(k, iss);
+ keys = [k];
} else {
- result.issues.push(iss);
+ return false;
+ }
+ for (const k of keys) {
+ if (!unrecKeys.has(k))
+ unrecKeys.set(k, {});
+ unrecKeys.get(k)[side] = true;
}
+ return true;
+ };
+ for (const iss of left.issues) {
+ if (!collect(iss, "l"))
+ result.issues.push(iss);
}
for (const iss of right.issues) {
- if (iss.code === "unrecognized_keys") {
- for (const k of iss.keys) {
- if (!unrecKeys.has(k))
- unrecKeys.set(k, {});
- unrecKeys.get(k).r = true;
- }
- } else {
+ if (!collect(iss, "r"))
result.issues.push(iss);
- }
}
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
- if (bothKeys.length && unrecIssue) {
- result.issues.push({ ...unrecIssue, keys: bothKeys });
+ if (bothKeys.length) {
+ const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
+ if (aggregated.length)
+ result.issues.push({ ...unrecIssue, keys: aggregated });
+ for (const k of bothKeys) {
+ if (!aggregated.includes(k) && keyIssues.has(k))
+ result.issues.push(keyIssues.get(k));
+ }
}
- if (aborted(result))
- return result;
const merged = mergeValues(left.value, right.value);
if (!merged.valid) {
+ if (aborted(result))
+ return result;
throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
}
result.value = merged.data;
return result;
}
-function handleOptionalResult(result, input) {
- if (input === undefined && (result.issues.length || result.fallback)) {
- return { issues: [], value: undefined };
- }
- return result;
+function handleOptionalResult(payload, result) {
+ payload.value = result.issues.length ? undefined : result.value;
+ return payload;
}
function handleDefaultResult(payload, def) {
if (payload.value === undefined) {
@@ -68934,15 +69390,33 @@ function handleNonOptionalResult(payload, inst) {
}
return payload;
}
+function handleCatchResult(payload, result, def, ctx) {
+ if (!result.issues.length) {
+ payload.value = result.value;
+ if (result.memo)
+ payload.memo = true;
+ return payload;
+ }
+ payload.value = def.catchValue({
+ ...result,
+ value: payload.value,
+ error: {
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ },
+ input: payload.value
+ });
+ return payload;
+}
function handlePipeResult(left, next, ctx) {
- if (left.issues.length) {
+ if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
left.aborted = true;
return left;
}
- return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
}
function handleReadonlyResult(payload) {
- payload.value = Object.freeze(payload.value);
+ if (!payload.memo)
+ payload.value = Object.freeze(payload.value);
return payload;
}
function handleRefineResult(result, payload, input, inst) {
@@ -68959,11 +69433,10 @@ function handleRefineResult(result, payload, input, inst) {
payload.issues.push(issue(_iss));
}
}
-var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodUnknown, $ZodNever, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodPreprocess, $ZodReadonly, $ZodCustom;
+var $ZodType, toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT = 1, URL_UNPARSEABLE = 2, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodUnknown, $ZodNever, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodPreprocess, $ZodReadonly, $ZodCustom;
var init_schemas = __esm(() => {
init_checks();
init_core();
- init_parse();
init_regexes();
init_util();
init_versions();
@@ -68974,10 +69447,8 @@ var init_schemas = __esm(() => {
inst._zod.def = def;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
- const checks = [...inst._zod.def.checks ?? []];
- if (inst._zod.traits.has("$ZodCheck")) {
- checks.unshift(inst);
- }
+ const defChecks = inst._zod.def.checks;
+ const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];
for (const ch of checks) {
for (const fn of ch._zod.onattach) {
fn(inst);
@@ -68990,6 +69461,8 @@ var init_schemas = __esm(() => {
});
} else {
const runChecks = (payload, checks, ctx) => {
+ if (payload.memo)
+ return payload;
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
@@ -69013,6 +69486,7 @@ var init_schemas = __esm(() => {
const nextLen = payload.issues.length;
if (nextLen === currLen)
return;
+ attachSchema(payload.issues, currLen, inst);
if (!isAborted)
isAborted = aborted(payload, currLen);
});
@@ -69020,6 +69494,7 @@ var init_schemas = __esm(() => {
const nextLen = payload.issues.length;
if (nextLen === currLen)
continue;
+ attachSchema(payload.issues, currLen, inst);
if (!isAborted)
isAborted = aborted(payload, currLen);
}
@@ -69066,22 +69541,17 @@ var init_schemas = __esm(() => {
return runChecks(result, checks, ctx);
};
}
- defineLazy(inst, "~standard", () => ({
- validate: (value) => {
- try {
- const r = safeParse(inst, value);
- return r.success ? { value: r.data } : { issues: r.error?.issues };
- } catch (_) {
- return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
- }
- },
- vendor: "zod",
- version: 1
- }));
+ }, {
+ get "~standard"() {
+ return hide(this, "~standard", standardProps(this));
+ },
+ set "~standard"(value) {
+ own(this, "~standard", value);
+ }
});
$ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
+ inst._zod.pattern = def.pattern ?? anyString;
inst._zod.parse = (payload, _) => {
if (def.coerce)
try {
@@ -69130,58 +69600,61 @@ var init_schemas = __esm(() => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
+ asciiTabOrNewline = /[\t\n\r]/g;
$ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const trimmed = payload.value.trim();
- if (!def.normalize && def.protocol?.source === httpProtocol.source) {
- if (!/^https?:\/\//i.test(trimmed)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid URL format",
- input: payload.value,
- inst,
- continue: !def.abort
- });
- return;
- }
+ const url = validateURL(trimmed, def);
+ if (url === URL_BAD_FORMAT) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid URL format",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
}
- const url = new URL(trimmed);
- if (def.hostname) {
- def.hostname.lastIndex = 0;
- if (!def.hostname.test(url.hostname)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid hostname",
- pattern: def.hostname.source,
- input: payload.value,
- inst,
- continue: !def.abort
- });
- }
+ if (url === URL_UNPARSEABLE) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
}
- if (def.protocol) {
- def.protocol.lastIndex = 0;
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid protocol",
- pattern: def.protocol.source,
- input: payload.value,
- inst,
- continue: !def.abort
- });
- }
+ if (url === true) {
+ payload.value = stripTabAndNewline(trimmed);
+ return;
}
- if (def.normalize) {
- payload.value = url.href;
- } else {
- payload.value = trimmed;
+ if (def.hostname && !urlHostnameOk(url, def.hostname)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid hostname",
+ pattern: def.hostname.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
}
+ if (def.protocol && !urlProtocolOk(url, def.protocol)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid protocol",
+ pattern: def.protocol.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
return;
} catch (_) {
payload.issues.push({
@@ -69199,7 +69672,9 @@ var init_schemas = __esm(() => {
$ZodStringFormat.init(inst, def);
});
$ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
- def.pattern ?? (def.pattern = nanoid);
+ if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))
+ throw new Error(`Invalid nanoid length: ${def.length}`);
+ def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length));
$ZodStringFormat.init(inst, def);
});
$ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
@@ -69241,16 +69716,13 @@ var init_schemas = __esm(() => {
$ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.format = `ipv4`;
});
+ ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
$ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.format = `ipv6`;
inst._zod.check = (payload) => {
- try {
- new URL(`http://[${payload.value}]`);
- } catch {
+ if (!isValidIPv6(payload.value)) {
payload.issues.push({
code: "invalid_format",
format: "ipv6",
@@ -69269,20 +69741,7 @@ var init_schemas = __esm(() => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
- const parts = payload.value.split("/");
- try {
- if (parts.length !== 2)
- throw new Error;
- const [address, prefix] = parts;
- if (!prefix)
- throw new Error;
- const prefixNum = Number(prefix);
- if (`${prefixNum}` !== prefix)
- throw new Error;
- if (prefixNum < 0 || prefixNum > 128)
- throw new Error;
- new URL(`http://[${address}]`);
- } catch {
+ if (!isValidCIDRv6(payload.value)) {
payload.issues.push({
code: "invalid_format",
format: "cidrv6",
@@ -69293,10 +69752,10 @@ var init_schemas = __esm(() => {
}
};
});
+ base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
$ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
- def.pattern ?? (def.pattern = base64);
+ def.pattern ?? (def.pattern = base64Charset);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.contentEncoding = "base64";
inst._zod.check = (payload) => {
if (isValidBase64(payload.value))
return;
@@ -69309,10 +69768,10 @@ var init_schemas = __esm(() => {
});
};
});
+ base64urlCharset = /^[A-Za-z0-9_-]*$/;
$ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
- def.pattern ?? (def.pattern = base64url);
+ def.pattern ?? (def.pattern = base64urlCharset);
$ZodStringFormat.init(inst, def);
- inst._zod.bag.contentEncoding = "base64url";
inst._zod.check = (payload) => {
if (isValidBase64URL(payload.value))
return;
@@ -69345,7 +69804,7 @@ var init_schemas = __esm(() => {
});
$ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.pattern = inst._zod.bag.pattern ?? number;
+ inst._zod.pattern = number;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce)
try {
@@ -69355,7 +69814,7 @@ var init_schemas = __esm(() => {
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
return payload;
}
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined;
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : undefined : undefined;
payload.issues.push({
expected: "number",
code: "invalid_type",
@@ -69408,6 +69867,8 @@ var init_schemas = __esm(() => {
});
$ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
$ZodType.init(inst, def);
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!Array.isArray(input)) {
@@ -69419,8 +69880,9 @@ var init_schemas = __esm(() => {
});
return payload;
}
- payload.value = Array(input.length);
+ payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);
const proms = [];
+ const abortEarly = ctx?.abortEarly;
for (let i = 0;i < input.length; i++) {
const item = input[i];
const result = def.element._zod.run({
@@ -69431,6 +69893,8 @@ var init_schemas = __esm(() => {
proms.push(result.then((result) => handleArrayResult(result, payload, i)));
} else {
handleArrayResult(result, payload, i);
+ if (abortEarly && result.issues.length !== 0 && aborted(result))
+ break;
}
}
if (proms.length) {
@@ -69439,31 +69903,35 @@ var init_schemas = __esm(() => {
return payload;
};
});
+ NO_SYMBOL_KEYS = [];
$ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
const desc = Object.getOwnPropertyDescriptor(def, "shape");
- if (!desc?.get) {
- const sh = def.shape;
- Object.defineProperty(def, "shape", {
- get: () => {
- const newSh = { ...sh };
- Object.defineProperty(def, "shape", {
- value: newSh
- });
- return newSh;
- }
- });
+ const sh = desc?.get ? desc.get.raw : def.shape ?? {};
+ if (sh) {
+ const get = () => {
+ const newSh = { ...sh };
+ Object.defineProperty(def, "shape", { value: newSh });
+ get.raw = newSh;
+ return newSh;
+ };
+ get.raw = sh;
+ Object.defineProperty(def, "shape", { get });
}
const _normalized = cached(() => normalizeDef(def));
- defineLazy(inst._zod, "propValues", () => {
- const shape = def.shape;
+ defineLazyInternal(inst, "propValues", (zod) => {
+ const shape = zod.def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
- propValues[key] ?? (propValues[key] = new Set);
+ if (!Object.prototype.hasOwnProperty.call(propValues, key)) {
+ assignProp(propValues, key, new Set);
+ }
for (const v of field.values)
propValues[key].add(v);
+ if (field.optin !== undefined)
+ propValues[key].add(undefined);
}
}
return propValues;
@@ -69471,6 +69939,8 @@ var init_schemas = __esm(() => {
const isObject2 = isObject;
const catchall = def.catchall;
let value;
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
@@ -69483,79 +69953,93 @@ var init_schemas = __esm(() => {
});
return payload;
}
- payload.value = {};
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const proms = [];
const shape = value.shape;
- for (const key of value.keys) {
+ const abortEarly = ctx?.abortEarly;
+ let seen = payload.issues.length;
+ for (const key of value.allKeys) {
+ if (abortEarly && payload.issues.length !== seen) {
+ if (aborted(payload, seen))
+ break;
+ seen = payload.issues.length;
+ }
+ if (key === "__proto__")
+ continue;
const el = shape[key];
- const isOptionalIn = el._zod.optin === "optional";
- const isOptionalOut = el._zod.optout === "optional";
+ const optin = el._zod.optin;
+ const optout = el._zod.optout;
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
} else {
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ handlePropertyResult(r, payload, key, input, optin, optout);
}
}
if (!catchall) {
return proms.length ? Promise.all(proms).then(() => payload) : payload;
}
- return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
};
});
$ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
$ZodObject.init(inst, def);
const superParse = inst._zod.parse;
const _normalized = cached(() => normalizeDef(def));
+ const memo = globalConfig.memoizer;
const generateFastpass = (shape) => {
- const doc = new Doc(["shape", "payload", "ctx"]);
const normalized = _normalized.value;
- const parseStr = (key) => {
- const k = esc(key);
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
- };
+ const syms = normalized.symbolKeys;
+ const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms });
+ const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
+ const prefixStr = (id, k) => `
+ let ${id}_ab = false;
+ for (let i = 0; i < ${id}.issues.length; i++) {
+ const iss = ${id}.issues[i];
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
+ payload.issues.push(iss);
+ if (iss.continue !== true) ${id}_ab = true;
+ }
+ if (${id}_ab && ctx && ctx.abortEarly) {
+ payload.value = newResult;
+ return payload;
+ }`;
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
- for (const key of normalized.keys) {
+ for (const key of normalized.allKeys) {
ids[key] = `key_${counter++}`;
}
- doc.write(`const newResult = {};`);
- for (const key of normalized.keys) {
+ doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);
+ for (const key of normalized.allKeys) {
+ if (key === "__proto__")
+ continue;
const id = ids[key];
- const k = esc(key);
+ const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
+ const isPresent = `${k} in input`;
const schema = shape[key];
- const isOptionalIn = schema?._zod?.optin === "optional";
+ const optin = schema?._zod?.optin;
+ const isOptionalIn = optin !== undefined;
const isOptionalOut = schema?._zod?.optout === "optional";
- doc.write(`const ${id} = ${parseStr(key)};`);
+ doc.write(`const ${id} = ${parseStr(k)};`);
if (isOptionalIn && isOptionalOut) {
+ const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
doc.write(`
- if (${id}.issues.length) {
- if (${k} in input) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ const ${id}_present = ${isPresent};
+ if (!${id}.issues.length || ${id}_present) {
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
- }
-
- if (${id}.value === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
+
+ if (${assign}) {
+ newResult[${k}] = ${id}.value;
}
- } else {
- newResult[${k}] = ${id}.value;
}
-
+
`);
} else if (!isOptionalIn) {
doc.write(`
- const ${id}_present = ${k} in input;
- if (${id}.issues.length) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
+ const ${id}_present = ${isPresent};
+ if (${id}.issues.length) {${prefixStr(id, k)}
}
if (!${id}_present && !${id}.issues.length) {
payload.issues.push({
@@ -69564,41 +70048,36 @@ var init_schemas = __esm(() => {
input: undefined,
path: [${k}]
});
+ if (ctx && ctx.abortEarly) {
+ payload.value = newResult;
+ return payload;
+ }
}
if (${id}_present) {
- if (${id}.value === undefined) {
- newResult[${k}] = undefined;
- } else {
- newResult[${k}] = ${id}.value;
- }
+ newResult[${k}] = ${id}.value;
}
`);
} else {
doc.write(`
- if (${id}.issues.length) {
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}]
- })));
- }
-
- if (${id}.value === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
- }
- } else {
+ if (${id}.issues.length) {${prefixStr(id, k)}
+ }
+ `);
+ if (optin === "defaulted") {
+ doc.write(`newResult[${k}] = ${id}.value;`);
+ } else {
+ doc.write(`
+ if (${id}.value !== undefined || ${isPresent}) {
newResult[${k}] = ${id}.value;
}
-
`);
+ }
}
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
- const fn = doc.compile();
- return (payload, ctx) => fn(shape, payload, ctx);
+ return doc.compile();
};
let fastpass;
const isObject2 = isObject;
@@ -69625,24 +70104,24 @@ var init_schemas = __esm(() => {
payload = fastpass(payload, ctx);
if (!catchall)
return payload;
- return handleCatchall([], input, payload, ctx, value, inst);
+ return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);
}
return superParse(payload, ctx);
};
});
$ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "values", () => {
- if (def.options.every((o) => o._zod.values)) {
- return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
+ defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== undefined) ? "optional" : undefined);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
+ defineLazyInternal(inst, "values", (zod) => {
+ if (zod.def.options.every((o) => o._zod.values)) {
+ return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));
}
return;
});
- defineLazy(inst._zod, "pattern", () => {
- if (def.options.every((o) => o._zod.pattern)) {
- const patterns = def.options.map((o) => o._zod.pattern);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ if (zod.def.options.every((o) => o._zod.pattern)) {
+ const patterns = zod.def.options.map((o) => o._zod.pattern);
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
}
return;
@@ -69679,38 +70158,35 @@ var init_schemas = __esm(() => {
def.inclusive = false;
$ZodUnion.init(inst, def);
const _super = inst._zod.parse;
- defineLazy(inst._zod, "propValues", () => {
+ defineLazyInternal(inst, "propValues", (zod) => {
const propValues = {};
- for (const option of def.options) {
+ let undefinedCount = 0;
+ for (const option of zod.def.options) {
const pv = option._zod.propValues;
if (!pv || Object.keys(pv).length === 0)
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
+ if (pv[zod.def.discriminator]?.has(undefined))
+ undefinedCount++;
for (const [k, v] of Object.entries(pv)) {
- if (!propValues[k])
- propValues[k] = new Set;
+ if (!Object.prototype.hasOwnProperty.call(propValues, k)) {
+ assignProp(propValues, k, new Set);
+ }
for (const val of v) {
propValues[k].add(val);
}
}
}
+ if (!zod.def.unionFallback && undefinedCount > 1)
+ propValues[zod.def.discriminator]?.delete(undefined);
return propValues;
});
- const disc = cached(() => {
- const opts = def.options;
- const map = new Map;
- for (const o of opts) {
- const values = o._zod.propValues?.[def.discriminator];
- if (!values || values.size === 0)
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
- for (const v of values) {
- if (map.has(v)) {
- throw new Error(`Duplicate discriminator value "${String(v)}"`);
- }
- map.set(v, o);
- }
+ def.options.forEach((option, i) => {
+ const propShape = rawShape(option._zod.def);
+ if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {
+ throw new Error(`Invalid discriminated union option at index "${i}"`);
}
- return map;
});
+ const disc = cached(() => discriminatorMap(def));
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isObject(input)) {
@@ -69722,8 +70198,9 @@ var init_schemas = __esm(() => {
});
return payload;
}
- const opt = disc.value.get(input?.[def.discriminator]);
- if (opt) {
+ const value = input?.[def.discriminator];
+ const opt = disc.value.get(value);
+ if (opt && (value !== undefined || ctx.direction !== "backward")) {
return opt._zod.run(payload, ctx);
}
if (def.unionFallback || ctx.direction === "backward") {
@@ -69734,7 +70211,7 @@ var init_schemas = __esm(() => {
errors: [],
note: "No matching discriminator",
discriminator: def.discriminator,
- options: Array.from(disc.value.keys()),
+ options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),
input,
path: [def.discriminator],
inst
@@ -69759,6 +70236,8 @@ var init_schemas = __esm(() => {
});
$ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
$ZodType.init(inst, def);
+ const memo = globalConfig.memoizer;
+ memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isPlainObject3(input)) {
@@ -69772,12 +70251,14 @@ var init_schemas = __esm(() => {
}
const proms = [];
const values = def.keyType._zod.values;
- if (values) {
- payload.value = {};
+ if (values && !def.partial) {
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const recordKeys = new Set;
for (const key of values) {
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
recordKeys.add(typeof key === "number" ? key.toString() : key);
+ if (key === "__proto__")
+ continue;
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
@@ -69794,6 +70275,8 @@ var init_schemas = __esm(() => {
continue;
}
const outKey = keyResult.value;
+ if (outKey === "__proto__")
+ continue;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
@@ -69813,8 +70296,14 @@ var init_schemas = __esm(() => {
let unrecognized;
for (const key in input) {
if (!recordKeys.has(key)) {
- unrecognized = unrecognized ?? [];
- unrecognized.push(key);
+ if (def.mode === "loose") {
+ if (key === "__proto__")
+ continue;
+ payload.value[key] = input[key];
+ } else {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
+ }
}
}
if (unrecognized && unrecognized.length > 0) {
@@ -69822,11 +70311,13 @@ var init_schemas = __esm(() => {
code: "unrecognized_keys",
input,
inst,
- keys: unrecognized
+ keys: unrecognized,
+ continue: true
});
}
} else {
- payload.value = {};
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
+ let unrecognized;
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__")
continue;
@@ -69849,6 +70340,9 @@ var init_schemas = __esm(() => {
if (keyResult.issues.length) {
if (def.mode === "loose") {
payload.value[key] = input[key];
+ } else if (values) {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
} else {
payload.issues.push({
code: "invalid_key",
@@ -69861,21 +70355,33 @@ var init_schemas = __esm(() => {
}
continue;
}
+ const outKey = keyResult.value;
+ if (outKey === "__proto__")
+ continue;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
if (result.issues.length) {
payload.issues.push(...prefixIssues(key, result.issues));
}
- payload.value[keyResult.value] = result.value;
+ payload.value[outKey] = result.value;
}));
} else {
if (result.issues.length) {
payload.issues.push(...prefixIssues(key, result.issues));
}
- payload.value[keyResult.value] = result.value;
+ payload.value[outKey] = result.value;
}
}
+ if (unrecognized && unrecognized.length > 0) {
+ payload.issues.push({
+ code: "unrecognized_keys",
+ input,
+ inst,
+ keys: unrecognized,
+ continue: true
+ });
+ }
}
if (proms.length) {
return Promise.all(proms).then(() => payload);
@@ -69888,7 +70394,10 @@ var init_schemas = __esm(() => {
const values = getEnumValues(def.entries);
const valuesSet = new Set(values);
inst._zod.values = valuesSet;
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k));
+ return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$");
+ });
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (valuesSet.has(input)) {
@@ -69905,12 +70414,12 @@ var init_schemas = __esm(() => {
});
$ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
$ZodType.init(inst, def);
- if (def.values.length === 0) {
- throw new Error("Cannot create literal schema with no valid values");
- }
const values = new Set(def.values);
inst._zod.values = values;
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const vals = zod.def.values;
+ return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$");
+ });
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (values.has(input)) {
@@ -69928,6 +70437,7 @@ var init_schemas = __esm(() => {
$ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
+ globalConfig.memoizer?.guard(inst);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
throw new $ZodEncodeError(inst.constructor.name);
@@ -69937,7 +70447,6 @@ var init_schemas = __esm(() => {
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
return output.then((output) => {
payload.value = output;
- payload.fallback = true;
return payload;
});
}
@@ -69945,53 +70454,51 @@ var init_schemas = __esm(() => {
throw new $ZodAsyncError;
}
payload.value = _out;
- payload.fallback = true;
return payload;
};
});
$ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
inst._zod.optout = "optional";
- defineLazy(inst._zod, "values", () => {
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
+ defineLazyInternal(inst, "values", (zod) => {
+ const values = zod.def.innerType._zod.values;
+ return values ? new Set([...values, undefined]) : undefined;
});
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def.innerType._zod.pattern;
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
});
inst._zod.parse = (payload, ctx) => {
- if (def.innerType._zod.optin === "optional") {
- const input = payload.value;
- const result = def.innerType._zod.run(payload, ctx);
- if (result instanceof Promise)
- return result.then((r) => handleOptionalResult(r, input));
- return handleOptionalResult(result, input);
- }
if (payload.value === undefined) {
- return payload;
+ if (def.innerType._zod.optin !== "defaulted")
+ return payload;
+ const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ return result.then((result) => handleOptionalResult(payload, result));
+ return handleOptionalResult(payload, result);
}
return def.innerType._zod.run(payload, ctx);
};
});
$ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
$ZodOptional.init(inst, def);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
- defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
+ defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern);
inst._zod.parse = (payload, ctx) => {
return def.innerType._zod.run(payload, ctx);
};
});
$ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def.innerType._zod.pattern;
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
+ defineLazyInternal(inst, "pattern", (zod) => {
+ const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
});
- defineLazy(inst._zod, "values", () => {
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
+ defineLazyInternal(inst, "values", (zod) => {
+ return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === null)
@@ -70001,8 +70508,8 @@ var init_schemas = __esm(() => {
});
$ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.optin = "defaulted";
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -70020,8 +70527,8 @@ var init_schemas = __esm(() => {
});
$ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.optin = "defaulted";
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -70034,8 +70541,8 @@ var init_schemas = __esm(() => {
});
$ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "values", () => {
- const v = def.innerType._zod.values;
+ defineLazyInternal(inst, "values", (zod) => {
+ const v = zod.def.innerType._zod.values;
return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
});
inst._zod.parse = (payload, ctx) => {
@@ -70048,52 +70555,26 @@ var init_schemas = __esm(() => {
});
$ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
}
- const result = def.innerType._zod.run(payload, ctx);
+ const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
if (result instanceof Promise) {
- return result.then((result) => {
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- payload.fallback = true;
- }
- return payload;
- });
- }
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- payload.fallback = true;
+ return result.then((result) => handleCatchResult(payload, result, def, ctx));
}
- return payload;
+ return handleCatchResult(payload, result, def, ctx);
};
});
$ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "values", () => def.in._zod.values);
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
+ defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
const right = def.out._zod.run(payload, ctx);
@@ -70114,10 +70595,10 @@ var init_schemas = __esm(() => {
});
$ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
- defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
- defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues);
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin);
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
return def.innerType._zod.run(payload, ctx);
@@ -70147,7 +70628,276 @@ var init_schemas = __esm(() => {
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/en.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/memoizer.js
+function isRef(value) {
+ return value !== null && typeof value === "object";
+}
+function cloneIssues(issues) {
+ return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
+}
+function isRecursive(inst, stack, resolve) {
+ const cached = recursive.get(inst);
+ if (cached !== undefined)
+ return cached ? PROVEN : NONE;
+ if (stack.has(inst))
+ return PROVEN;
+ stack.add(inst);
+ let result = NONE;
+ const check = (child) => {
+ if (result !== PROVEN && child?._zod) {
+ const answer = isRecursive(child, stack, resolve);
+ if (answer > result)
+ result = answer;
+ }
+ };
+ const shape = (sh, spread) => {
+ let answer = NONE;
+ for (const key of Reflect.ownKeys(sh)) {
+ const desc = Object.getOwnPropertyDescriptor(sh, key);
+ if (spread && !desc.enumerable)
+ continue;
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
+ if (child > answer)
+ answer = child;
+ }
+ return answer;
+ };
+ const merge = (answer) => {
+ if (answer > result)
+ result = answer;
+ };
+ const def = inst._zod.def;
+ const kind = def.type;
+ switch (kind) {
+ case "object": {
+ const raw = rawShape(def);
+ merge(raw ? shape(raw, true) : ASSUMED);
+ check(def.catchall);
+ break;
+ }
+ case "array":
+ check(def.element);
+ break;
+ case "tuple":
+ for (const el of def.items)
+ check(el);
+ check(def.rest);
+ break;
+ case "record":
+ case "map":
+ check(def.keyType);
+ check(def.valueType);
+ break;
+ case "set":
+ check(def.valueType);
+ break;
+ case "union":
+ for (const el of def.options)
+ check(el);
+ break;
+ case "intersection":
+ check(def.left);
+ check(def.right);
+ break;
+ case "optional":
+ case "nullable":
+ case "default":
+ case "prefault":
+ case "catch":
+ case "readonly":
+ case "nonoptional":
+ case "promise":
+ case "success":
+ check(def.innerType);
+ break;
+ case "pipe":
+ check(def.in);
+ check(def.out);
+ break;
+ case "function":
+ check(def.input);
+ check(def.output);
+ break;
+ case "lazy": {
+ const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);
+ merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
+ break;
+ }
+ case "template_literal":
+ case "string":
+ case "number":
+ case "int":
+ case "boolean":
+ case "bigint":
+ case "symbol":
+ case "undefined":
+ case "null":
+ case "void":
+ case "never":
+ case "any":
+ case "unknown":
+ case "date":
+ case "nan":
+ case "enum":
+ case "literal":
+ case "file":
+ case "transform":
+ case "custom":
+ break;
+ default: {
+ for (const key in def) {
+ const desc = Object.getOwnPropertyDescriptor(def, key);
+ if (!desc || desc.get)
+ continue;
+ const value = desc.value;
+ if (!value || typeof value !== "object")
+ continue;
+ if (value._zod)
+ check(value);
+ else if (Array.isArray(value))
+ for (const el of value)
+ check(el);
+ }
+ }
+ }
+ stack.delete(inst);
+ return settle(inst, result);
+}
+function settle(inst, answer) {
+ if (answer !== ASSUMED)
+ recursive.set(inst, answer === PROVEN);
+ return answer;
+}
+function bucketFor(state, inst) {
+ let bucket = state.buckets.get(inst);
+ if (!bucket) {
+ bucket = new WeakMap;
+ state.buckets.set(inst, bucket);
+ }
+ return bucket;
+}
+function memoizer() {
+ return memo;
+}
+function isBackEdge(ctx, value) {
+ const backEdges = ctx[STATE]?.backEdges;
+ return backEdges !== undefined && isRef(value) && backEdges.has(value);
+}
+var $ZodCyclicError, STATE = "~memo", NO_ISSUES, recursive, NONE = 0, ASSUMED = 1, PROVEN = 2, handoff, open, memo;
+var init_memoizer = __esm(() => {
+ init_util();
+ $ZodCyclicError = class $ZodCyclicError extends Error {
+ constructor() {
+ super(`Cannot parse a reference cycle that closes through a transform`);
+ this.name = "ZodCyclicError";
+ }
+ };
+ NO_ISSUES = [];
+ recursive = /* @__PURE__ */ new WeakMap;
+ open = [];
+ memo = {
+ alloc(_inst, payload, empty) {
+ const bucket = handoff;
+ if (!bucket)
+ return empty;
+ handoff = undefined;
+ const entry = { value: empty, issues: null };
+ bucket.set(payload.value, entry);
+ open.push(entry);
+ return empty;
+ },
+ guard(inst) {
+ var _a;
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
+ inst._zod.deferred.push(() => {
+ const base = inst._zod.parse;
+ const wrapped = (payload, ctx) => {
+ if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value))
+ throw new $ZodCyclicError;
+ return base(payload, ctx);
+ };
+ inst._zod.parse = wrapped;
+ if (inst._zod.run === base)
+ inst._zod.run = wrapped;
+ });
+ },
+ attach(inst) {
+ var _a;
+ let isRecursiveInst;
+ let rechecked = false;
+ let lastCtx;
+ let lastBucket;
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
+ inst._zod.deferred.push(() => {
+ const base = inst._zod.parse;
+ const wrapped = (payload, ctx) => {
+ if (isRecursiveInst === undefined) {
+ const walked = isRecursive(inst, new Set, false);
+ if (walked === NONE) {
+ inst._zod.parse = base;
+ if (inst._zod.run === wrapped)
+ inst._zod.run = base;
+ return base(payload, ctx);
+ }
+ if (walked === PROVEN || rechecked)
+ isRecursiveInst = true;
+ else
+ rechecked = true;
+ }
+ const input = payload.value;
+ if (!isRef(input))
+ return base(payload, ctx);
+ let state = ctx[STATE];
+ if (!state) {
+ state = { buckets: new WeakMap, backEdges: undefined };
+ ctx[STATE] = state;
+ }
+ let bucket;
+ if (lastCtx === ctx) {
+ bucket = lastBucket;
+ } else {
+ bucket = bucketFor(state, inst);
+ lastCtx = ctx;
+ lastBucket = bucket;
+ }
+ const hit = bucket.get(input);
+ if (hit) {
+ payload.value = hit.value;
+ if (hit.issues) {
+ if (hit.issues.length)
+ payload.issues.push(...cloneIssues(hit.issues));
+ } else {
+ payload.memo = true;
+ state.backEdges ?? (state.backEdges = new WeakSet);
+ state.backEdges.add(hit.value);
+ }
+ return payload;
+ }
+ handoff = bucket;
+ const depth = open.length;
+ const result = base(payload, ctx);
+ handoff = undefined;
+ const entry = open.length > depth ? open.pop() : undefined;
+ if (result instanceof Promise) {
+ return result.then((r) => {
+ if (entry)
+ entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
+ return r;
+ });
+ }
+ if (entry)
+ entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
+ return result;
+ };
+ inst._zod.parse = wrapped;
+ if (inst._zod.run === base)
+ inst._zod.run = wrapped;
+ });
+ }
+ };
+});
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/en.js
function en_default() {
return {
localeError: error()
@@ -70192,18 +70942,27 @@ var error = () => {
base64url: "base64url-encoded string",
json_string: "JSON string",
e164: "E.164 number",
+ currency_code: "currency code",
+ credit_card: "credit card number",
+ iban: "IBAN",
jwt: "JWT",
template_literal: "input"
};
const TypeDictionary = {
nan: "NaN"
};
+ function getTypeName(type, input) {
+ if (type === "number" && typeof input === "number" && !Number.isFinite(input)) {
+ return String(input);
+ }
+ return TypeDictionary[type] ?? type;
+ }
return (issue) => {
switch (issue.code) {
case "invalid_type": {
- const expected = TypeDictionary[issue.expected] ?? issue.expected;
+ const expected = getTypeName(issue.expected);
const receivedType = parsedType(issue.input);
- const received = TypeDictionary[receivedType] ?? receivedType;
+ const received = getTypeName(receivedType, issue.input);
return `Invalid input: expected ${expected}, received ${received}`;
}
case "invalid_value":
@@ -70211,14 +70970,14 @@ var error = () => {
return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
case "too_big": {
- const adj = issue.inclusive ? "<=" : "<";
+ const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
- const adj = issue.inclusive ? ">=" : ">";
+ const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
@@ -70249,6 +71008,9 @@ var error = () => {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `Invalid discriminator value. Expected ${opts}`;
}
+ if (issue.inclusive === false) {
+ return "Invalid input: more than one option matched";
+ }
return "Invalid input";
case "invalid_element":
return `Invalid value in ${issue.origin}`;
@@ -70261,10 +71023,10 @@ var init_en = __esm(() => {
init_util();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/index.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/locales/index.js
var init_locales = () => {};
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/registries.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/registries.js
class $ZodRegistry {
constructor() {
this._map = new WeakMap;
@@ -70308,20 +71070,61 @@ class $ZodRegistry {
function registry() {
return new $ZodRegistry;
}
-var _a2, $output, $input, globalRegistry;
+var _a2, globalRegistry;
var init_registries = __esm(() => {
- $output = Symbol("ZodOutput");
- $input = Symbol("ZodInput");
(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
globalRegistry = globalThis.__zod_globalRegistry;
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/api.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/compile.js
+var INVALID2, FALLBACK_FLAG, WHEN_DEFAULTED_CHECKS, PATTERN_IS_COMPLETE;
+var init_compile = __esm(() => {
+ INVALID2 = Symbol.for("zod.compile.invalid");
+ FALLBACK_FLAG = Symbol.for("zod.compile.fallback");
+ WHEN_DEFAULTED_CHECKS = new Set([
+ "max_size",
+ "min_size",
+ "size_equals",
+ "max_length",
+ "min_length",
+ "length_equals"
+ ]);
+ PATTERN_IS_COMPLETE = new Set([
+ "cidrv4",
+ "cuid",
+ "cuid2",
+ "date",
+ "datetime",
+ "duration",
+ "e164",
+ "email",
+ "emoji",
+ "ends_with",
+ "guid",
+ "includes",
+ "ipv4",
+ "ksuid",
+ "lowercase",
+ "mac",
+ "nanoid",
+ "regex",
+ "starts_with",
+ "time",
+ "ulid",
+ "uppercase",
+ "uuid",
+ "xid"
+ ]);
+});
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/api.js
+function snapshotChecks(def) {
+ if (def.checks)
+ def.checks = [...def.checks];
+ return def;
+}
function _string(Class, params) {
- return new Class({
- type: "string",
- ...normalizeParams(params)
- });
+ return new Class(snapshotChecks({ type: "string", ...normalizeParams(params) }));
}
function _email(Class, params) {
return new Class({
@@ -70561,11 +71364,7 @@ function _isoDuration(Class, params) {
});
}
function _number(Class, params) {
- return new Class({
- type: "number",
- checks: [],
- ...normalizeParams(params)
- });
+ return new Class(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) }));
}
function _int(Class, params) {
return new Class({
@@ -70747,7 +71546,8 @@ function _superRefine(fn, params) {
if (_issue.fatal)
_issue.continue = false;
_issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
+ if (!("input" in _issue))
+ _issue.input = payload.value;
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
@@ -70770,7 +71570,17 @@ var init_api = __esm(() => {
init_util();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/to-json-schema.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/to-json-schema.js
+function assignProps(target, ...sources) {
+ for (const source of sources) {
+ for (const key of Reflect.ownKeys(source)) {
+ if (Object.prototype.propertyIsEnumerable.call(source, key)) {
+ assignProp(target, key, source[key]);
+ }
+ }
+ }
+ return target;
+}
function initializeContext(params) {
let target = params?.target ?? "draft-2020-12";
if (target === "draft-4")
@@ -70786,12 +71596,25 @@ function initializeContext(params) {
io: params?.io ?? "output",
counter: 0,
seen: new Map,
+ sharedDefsExtractedFor: undefined,
+ sharedEmitDoneFor: undefined,
cycles: params?.cycles ?? "ref",
reused: params?.reused ?? "inline",
+ intersections: [],
+ deferred: [],
external: params?.external ?? undefined
};
}
-function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
+function handleUnrepresentable(schema, ctx, json, params, message) {
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) : ctx.unrepresentable;
+ if (result === "any")
+ return false;
+ if (result === undefined || result === "throw")
+ throw new Error(message);
+ Object.assign(json, result);
+ return true;
+}
+function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {
var _a;
const def = schema._zod.def;
const seen = ctx.seen.get(schema);
@@ -70805,6 +71628,8 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
}
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
ctx.seen.set(schema, result);
+ ctx.sharedDefsExtractedFor = undefined;
+ ctx.sharedEmitDoneFor = undefined;
const overrideSchema = schema._zod.toJSONSchema?.();
if (overrideSchema) {
result.schema = overrideSchema;
@@ -70828,13 +71653,13 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
if (parent) {
if (!result.ref)
result.ref = parent;
- process3(parent, ctx, params);
+ processSchema(parent, ctx, params);
ctx.seen.get(parent).isParent = true;
}
}
const meta = ctx.metadataRegistry.get(schema);
if (meta)
- Object.assign(result.schema, meta);
+ assignProps(result.schema, meta);
if (ctx.io === "input" && isTransforming(schema)) {
delete result.schema.examples;
delete result.schema.default;
@@ -70845,10 +71670,15 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
const _result = ctx.seen.get(schema);
return _result.schema;
}
+function encodeJSONPointerSegment(segment) {
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
+}
function extractDefs(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root)
throw new Error("Unprocessed schema. This is a bug in Zod.");
+ if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)
+ return;
const idToSchema = new Map;
for (const entry of ctx.seen.entries()) {
const id = ctx.metadataRegistry.get(entry[0])?.id;
@@ -70870,15 +71700,15 @@ function extractDefs(ctx, schema) {
}
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
entry[1].defId = id;
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
- }
- if (entry[1] === root) {
- return { ref: "#" };
+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };
}
const uriPrefix = `#`;
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
+ if (entry[1] === root && !entry[1].schema.id) {
+ return { ref: uriPrefix };
+ }
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
- return { defId, ref: defUriPrefix + defId };
+ return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };
};
const extractToDef = (entry) => {
if (entry[1].schema.$ref) {
@@ -70928,10 +71758,117 @@ function extractDefs(ctx, schema) {
if (seen.count > 1) {
if (ctx.reused === "ref") {
extractToDef(entry);
+ }
+ }
+ }
+ if (ctx.external)
+ ctx.sharedDefsExtractedFor = ctx.external;
+}
+function compactTypeUnion(schema) {
+ const options = schema.anyOf;
+ if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)
+ return;
+ const types = [];
+ for (const option of options) {
+ if (!option || typeof option !== "object")
+ return;
+ compactTypeUnion(option);
+ const keys = Object.keys(option);
+ if (keys.length !== 1 || keys[0] !== "type")
+ return;
+ const type = option.type;
+ for (const member of Array.isArray(type) ? type : [type]) {
+ if (typeof member !== "string")
+ return;
+ if (!types.includes(member))
+ types.push(member);
+ }
+ }
+ delete schema.anyOf;
+ schema.type = types.length === 1 ? types[0] : types;
+}
+function undeclaredConstraint(member) {
+ const extra = member.additionalProperties;
+ if (extra === undefined || extra === false || typeof extra !== "object" || extra === null)
+ return null;
+ return Object.keys(extra).length ? extra : null;
+}
+function foldObjects(members) {
+ const objects = [];
+ for (const member of members) {
+ if (typeof member !== "object" || member.type !== "object")
+ return null;
+ for (const key in member) {
+ if (!FOLDABLE_KEYS.has(key))
+ return null;
+ }
+ objects.push(member);
+ }
+ const properties = {};
+ const required = new Set;
+ for (const object of objects) {
+ for (const key in object.properties) {
+ if (Object.prototype.hasOwnProperty.call(properties, key))
continue;
+ const parts = [];
+ for (const other of objects) {
+ const part = other.properties?.[key] ?? undeclaredConstraint(other);
+ if (part === null || part === undefined)
+ continue;
+ if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))
+ parts.push(part);
}
+ const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
+ assignProp(properties, key, merged);
}
+ for (const key of object.required ?? [])
+ required.add(key);
}
+ const folded = { type: "object", properties };
+ if (required.size)
+ folded.required = [...required];
+ if (objects.every((object) => object.additionalProperties === false)) {
+ folded.additionalProperties = false;
+ } else {
+ const constraints = [];
+ for (const object of objects) {
+ const constraint = undeclaredConstraint(object);
+ if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
+ constraints.push(constraint);
+ }
+ if (constraints.length === 1)
+ folded.additionalProperties = constraints[0];
+ else if (constraints.length > 1)
+ folded.additionalProperties = { allOf: constraints };
+ }
+ return folded;
+}
+function foldIntersection(json) {
+ const allOf = json.allOf;
+ if (!Array.isArray(allOf) || allOf.length < 2)
+ return;
+ for (const key of FOLDABLE_KEYS)
+ if (key in json)
+ return;
+ const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));
+ let folded = null;
+ if (!unions.length) {
+ folded = foldObjects(allOf);
+ } else {
+ const union = unions[0];
+ const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));
+ if (Object.keys(union).length !== 1)
+ return;
+ const rest = allOf.filter((m) => m !== union);
+ const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));
+ if (branches.some((b) => !b))
+ return;
+ folded = { [keyword]: branches };
+ }
+ if (!folded)
+ return;
+ delete json.allOf;
+ assignProps(json, folded);
}
function finalize(ctx, schema) {
const root = ctx.seen.get(schema);
@@ -70953,9 +71890,9 @@ function finalize(ctx, schema) {
schema.allOf = schema.allOf ?? [];
schema.allOf.push(refSchema);
} else {
- Object.assign(schema, refSchema);
+ assignProps(schema, refSchema);
}
- Object.assign(schema, _cached);
+ assignProps(schema, _cached);
const isParentRef = zodSchema._zod.parent === ref;
if (isParentRef) {
for (const key in schema) {
@@ -70999,8 +71936,36 @@ function finalize(ctx, schema) {
path: seen.path ?? []
});
};
- for (const entry of [...ctx.seen.entries()].reverse()) {
- flattenRef(entry[0]);
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
+ for (const entry of [...ctx.seen.entries()].reverse()) {
+ flattenRef(entry[0]);
+ }
+ if (ctx.target !== "openapi-3.0") {
+ for (const entry of ctx.seen.entries()) {
+ compactTypeUnion(entry[1].def ?? entry[1].schema);
+ }
+ }
+ for (const rewrite of ctx.deferred)
+ rewrite();
+ if (ctx.intersections.length) {
+ const carriers = new Map;
+ for (const seen of ctx.seen.values()) {
+ for (const json of [seen.schema, seen.def]) {
+ const allOf = json?.allOf;
+ if (!Array.isArray(allOf))
+ continue;
+ const existing = carriers.get(allOf);
+ if (existing)
+ existing.push(json);
+ else
+ carriers.set(allOf, [json]);
+ }
+ }
+ for (const allOf of ctx.intersections) {
+ for (const json of carriers.get(allOf) ?? [])
+ foldIntersection(json);
+ }
+ }
}
const result = {};
if (ctx.target === "draft-2020-12") {
@@ -71016,19 +71981,23 @@ function finalize(ctx, schema) {
throw new Error("Schema is missing an `id` property");
result.$id = ctx.external.uri(id);
}
- Object.assign(result, root.def ?? root.schema);
+ assignProps(result, root.defId ? root.schema : root.def ?? root.schema);
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
if (rootMetaId !== undefined && result.id === rootMetaId)
delete result.id;
const defs = ctx.external?.defs ?? {};
- for (const entry of ctx.seen.entries()) {
- const seen = entry[1];
- if (seen.def && seen.defId) {
- if (seen.def.id === seen.defId)
- delete seen.def.id;
- defs[seen.defId] = seen.def;
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
+ for (const entry of ctx.seen.entries()) {
+ const seen = entry[1];
+ if (seen.def && seen.defId) {
+ if (seen.def.id === seen.defId)
+ delete seen.def.id;
+ assignProp(defs, seen.defId, seen.def);
+ }
}
}
+ if (ctx.external)
+ ctx.sharedEmitDoneFor = ctx.external;
if (ctx.external) {} else {
if (Object.keys(defs).length > 0) {
if (ctx.target === "draft-2020-12") {
@@ -71070,7 +72039,7 @@ function isTransforming(_schema, _ctx) {
return isTransforming(def.valueType, ctx);
if (def.type === "lazy")
return isTransforming(def.getter(), ctx);
- if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") {
return isTransforming(def.innerType, ctx);
}
if (def.type === "intersection") {
@@ -71109,27 +72078,170 @@ function isTransforming(_schema, _ctx) {
}
return false;
}
-var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
+var FOLDABLE_KEYS, UNION_KEYS, createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
const ctx = initializeContext({ ...params, processors });
- process3(schema, ctx);
+ processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
}, createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
const { libraryOptions, target } = params ?? {};
const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
- process3(schema, ctx);
+ processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
var init_to_json_schema = __esm(() => {
init_registries();
+ init_util();
+ FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]);
+ UNION_KEYS = ["oneOf", "anyOf"];
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema-processors.js
-var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema-processors.js
+function aggregateChecks(schema) {
+ const agg = {};
+ const def = schema._zod.def;
+ const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
+ for (const ch of list)
+ contributors[ch._zod.def.check]?.(agg, ch._zod.def);
+ const bag = schema._zod.bag;
+ if (bag.minimum !== undefined)
+ narrowMin(agg, "minimum", bag.minimum);
+ if (bag.exclusiveMinimum !== undefined)
+ narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
+ if (bag.maximum !== undefined)
+ narrowMax(agg, "maximum", bag.maximum);
+ if (bag.exclusiveMaximum !== undefined)
+ narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
+ if (bag.multipleOf !== undefined)
+ addDivisor(agg, bag.multipleOf);
+ if (bag.format !== undefined) {
+ agg.format ?? (agg.format = bag.format);
+ if (bag.format.includes("int"))
+ agg.isInt = true;
+ }
+ if (bag.mime)
+ intersectMime(agg, bag.mime);
+ for (const pattern of bag.patterns ?? [])
+ addPattern(agg, pattern);
+ return agg;
+}
+function inputOptin(schema) {
+ const def = schema._zod.def;
+ if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) {
+ return inputOptin(def.out);
+ }
+ if (def.type === "catch") {
+ return inputOptin(def.innerType);
+ }
+ return schema._zod.optin;
+}
+function stringifyKeyNames(bySchema, json, visited) {
+ if (json.$ref) {
+ if (visited.has(json))
+ return json;
+ visited.add(json);
+ const def = bySchema.get(json)?.def;
+ if (!def)
+ return json;
+ const inlined = stringifyKeyNames(bySchema, def, visited);
+ return inlined === def ? json : inlined;
+ }
+ for (const keyword of ["anyOf", "oneOf"]) {
+ const branches = json[keyword];
+ if (!Array.isArray(branches))
+ continue;
+ const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
+ if (mapped.some((branch, i) => branch !== branches[i]))
+ json = { ...json, [keyword]: mapped };
+ }
+ const types = Array.isArray(json.type) ? json.type : [json.type];
+ const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
+ const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);
+ if (!numericType && !values?.some((v) => typeof v === "number"))
+ return json;
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
+ if (rest.enum)
+ rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
+ else if (typeof rest.const === "number")
+ rest.const = String(rest.const);
+ if (!numericType)
+ return rest;
+ rest.type = "string";
+ if (!values)
+ rest.pattern = (types.includes("number") ? number : integer).source;
+ return rest;
+}
+function rewriteKeyNames(ctx) {
+ const bySchema = new Map;
+ for (const entry of ctx.seen.values()) {
+ if (entry.def && !bySchema.has(entry.schema))
+ bySchema.set(entry.schema, entry);
+ }
+ const rewrites = new Map;
+ for (const record of pendingRecords.get(ctx) ?? []) {
+ const seen = ctx.seen.get(record);
+ const names = (seen?.def ?? seen?.schema)?.propertyNames;
+ if (!names || names === true || rewrites.has(names))
+ continue;
+ const rewritten = stringifyKeyNames(bySchema, names, new Set);
+ if (rewritten !== names)
+ rewrites.set(names, rewritten);
+ }
+ if (!rewrites.size)
+ return;
+ for (const entry of ctx.seen.values()) {
+ for (const carrier of [entry.schema, entry.def]) {
+ const rewritten = carrier && rewrites.get(carrier.propertyNames);
+ if (rewritten)
+ carrier.propertyNames = rewritten;
+ }
+ }
+}
+function serializeDefaultValue(value, schema, ctx, json, params) {
+ let unrepresentable = false;
+ const serialized = JSON.stringify(value, (_, val) => {
+ if (typeof val !== "bigint")
+ return val;
+ unrepresentable = true;
+ return null;
+ });
+ if (!unrepresentable)
+ return JSON.parse(serialized);
+ handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
+ return UNREPRESENTABLE_DEFAULT;
+}
+var narrowMin = (agg, key, value) => {
+ if (agg[key] === undefined || value > agg[key])
+ agg[key] = value;
+}, narrowMax = (agg, key, value) => {
+ if (agg[key] === undefined || value < agg[key])
+ agg[key] = value;
+}, narrowBoth = (agg, value) => {
+ narrowMin(agg, "minimum", value);
+ narrowMax(agg, "maximum", value);
+}, addDivisor = (agg, value) => {
+ agg.multipleOf ?? (agg.multipleOf = []);
+ if (!agg.multipleOf.includes(value))
+ agg.multipleOf.push(value);
+}, addPattern = (agg, pattern) => {
+ agg.patterns ?? (agg.patterns = new Set);
+ agg.patterns.add(pattern);
+}, intersectMime = (agg, mime) => {
+ agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
+}, setFormat = (agg, format) => {
+ agg.format = format;
+ if (format.includes("int"))
+ agg.isInt = true;
+}, minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum), maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum), formatContributor = (ranges) => (agg, def) => {
+ setFormat(agg, def.format);
+ const [minimum, maximum] = ranges[def.format];
+ narrowMin(agg, "minimum", minimum);
+ narrowMax(agg, "maximum", maximum);
+}, contributors, formatMap, exactPatterns, exactPattern = (p) => exactPatterns.get(p) ?? p, stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
- const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minLength = minimum;
if (typeof maximum === "number")
@@ -71138,32 +72250,29 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
json.format = formatMap[format] ?? format;
if (json.format === "")
delete json.format;
- if (format === "time") {
+ if (format === "time" || laxFormat) {
delete json.format;
}
}
if (contentEncoding)
json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
- const regexes = [...patterns];
- if (regexes.length === 1)
- json.pattern = regexes[0].source;
- else if (regexes.length > 1) {
+ const patternList = [...patterns].map(exactPattern);
+ if (patternList.length === 1)
+ json.pattern = patternList[0].source;
+ else if (patternList.length > 1) {
json.allOf = [
- ...regexes.map((regex) => ({
+ ...patternList.map((regex) => ({
...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
pattern: regex.source
}))
];
}
}
-}, numberProcessor = (schema, ctx, _json, _params) => {
+}, numberProcessor = (schema, ctx, _json, params) => {
const json = _json;
- const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
- if (typeof format === "string" && format.includes("int"))
- json.type = "integer";
- else
- json.type = "number";
+ const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
+ json.type = isInt ? "integer" : "number";
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
@@ -71187,8 +72296,20 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
} else if (typeof maximum === "number") {
json.maximum = maximum;
}
- if (typeof multipleOf === "number")
- json.multipleOf = multipleOf;
+ if (multipleOf) {
+ const divisors = new Set;
+ for (const divisor of multipleOf) {
+ if (Number.isFinite(divisor) && divisor !== 0)
+ divisors.add(Math.abs(divisor));
+ else
+ handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
+ }
+ const [first, ...rest] = divisors;
+ if (first !== undefined)
+ json.multipleOf = first;
+ if (rest.length)
+ json.allOf = [...json.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
+ }
}, booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
}, neverProcessor = (_schema, _ctx, json, _params) => {
@@ -71196,25 +72317,30 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}, unknownProcessor = (_schema, _ctx, _json, _params) => {}, enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = getEnumValues(def.entries);
+ if (values.length === 0) {
+ json.not = {};
+ return;
+ }
if (values.every((v) => typeof v === "number"))
json.type = "number";
if (values.every((v) => typeof v === "string"))
json.type = "string";
json.enum = values;
-}, literalProcessor = (schema, ctx, json, _params) => {
+}, literalProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
+ if (def.values.length === 0) {
+ json.not = {};
+ return;
+ }
const vals = [];
for (const val of def.values) {
if (val === undefined) {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Literal `undefined` cannot be represented in JSON Schema");
- }
+ if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema"))
+ return;
} else if (typeof val === "bigint") {
- if (ctx.unrepresentable === "throw") {
- throw new Error("BigInt literals cannot be represented in JSON Schema");
- } else {
- vals.push(Number(val));
- }
+ if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema"))
+ return;
+ vals.push(Number(val));
} else {
vals.push(val);
}
@@ -71238,50 +72364,48 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
json.type = "null";
json.enum = vals;
}
-}, customProcessor = (_schema, ctx, _json, _params) => {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Custom types cannot be represented in JSON Schema");
- }
-}, transformProcessor = (_schema, ctx, _json, _params) => {
- if (ctx.unrepresentable === "throw") {
- throw new Error("Transforms cannot be represented in JSON Schema");
- }
+}, customProcessor = (schema, ctx, json, params) => {
+ handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
+}, transformProcessor = (schema, ctx, json, params) => {
+ handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
}, arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
- const { minimum, maximum } = schema._zod.bag;
+ const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
- json.items = process3(def.element, ctx, {
+ json.items = processSchema(def.element, ctx, {
...params,
path: [...params.path, "items"]
});
}, objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
+ const shape = def.shape;
+ const symbolKeys = Object.getOwnPropertySymbols(shape);
+ if (symbolKeys.length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) {
+ return;
+ }
json.type = "object";
json.properties = {};
- const shape = def.shape;
for (const key in shape) {
- json.properties[key] = process3(shape[key], ctx, {
+ assignProp(json.properties, key, processSchema(shape[key], ctx, {
...params,
path: [...params.path, "properties", key]
- });
+ }));
}
- const allKeys = new Set(Object.keys(shape));
- const requiredKeys = new Set([...allKeys].filter((key) => {
- const v = def.shape[key]._zod;
- if (ctx.io === "input") {
- return v.optin === undefined;
- } else {
- return v.optout === undefined;
+ const requiredKeys = [];
+ for (const key of Object.keys(shape)) {
+ const field = def.shape[key];
+ if (ctx.io === "input" ? inputOptin(field) === undefined : field._zod.optout === undefined) {
+ requiredKeys.push(key);
}
- }));
- if (requiredKeys.size > 0) {
- json.required = Array.from(requiredKeys);
+ }
+ if (requiredKeys.length > 0) {
+ json.required = requiredKeys;
}
if (def.catchall?._zod.def.type === "never") {
json.additionalProperties = false;
@@ -71289,7 +72413,7 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
if (ctx.io === "output")
json.additionalProperties = false;
} else if (def.catchall) {
- json.additionalProperties = process3(def.catchall, ctx, {
+ json.additionalProperties = processSchema(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
@@ -71297,7 +72421,7 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}, unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const isExclusive = def.inclusive === false;
- const options = def.options.map((x, i) => process3(x, ctx, {
+ const options = def.options.map((x, i) => processSchema(x, ctx, {
...params,
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
}));
@@ -71308,11 +72432,11 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}
}, intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- const a = process3(def.left, ctx, {
+ const a = processSchema(def.left, ctx, {
...params,
path: [...params.path, "allOf", 0]
});
- const b = process3(def.right, ctx, {
+ const b = processSchema(def.right, ctx, {
...params,
path: [...params.path, "allOf", 1]
});
@@ -71322,44 +72446,52 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
...isSimpleIntersection(b) ? b.allOf : [b]
];
json.allOf = allOf;
-}, recordProcessor = (schema, ctx, _json, params) => {
+ ctx.intersections.push(allOf);
+}, pendingRecords, recordProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "object";
const keyType = def.keyType;
- const keyBag = keyType._zod.bag;
- const patterns = keyBag?.patterns;
+ const patterns = aggregateChecks(keyType).patterns;
if (def.mode === "loose" && patterns && patterns.size > 0) {
- const valueSchema = process3(def.valueType, ctx, {
+ const valueSchema = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "patternProperties", "*"]
});
json.patternProperties = {};
for (const pattern of patterns) {
- json.patternProperties[pattern.source] = valueSchema;
+ assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
}
} else {
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
- json.propertyNames = process3(def.keyType, ctx, {
+ json.propertyNames = processSchema(def.keyType, ctx, {
...params,
path: [...params.path, "propertyNames"]
});
+ let pending = pendingRecords.get(ctx);
+ if (!pending) {
+ pending = [];
+ pendingRecords.set(ctx, pending);
+ ctx.deferred.push(() => rewriteKeyNames(ctx));
+ }
+ pending.push(schema);
}
- json.additionalProperties = process3(def.valueType, ctx, {
+ json.additionalProperties = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
}
const keyValues = keyType._zod.values;
- if (keyValues) {
+ const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined;
+ if (keyValues && !def.partial && !omittableOnInput) {
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
if (validKeyValues.length > 0) {
- json.required = validKeyValues;
+ json.required = validKeyValues.map(String);
}
}
}, nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- const inner = process3(def.innerType, ctx, params);
+ const inner = processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
@@ -71369,56 +72501,87 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
}
}, nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
-}, defaultProcessor = (schema, ctx, json, params) => {
+}, UNREPRESENTABLE_DEFAULT, defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
- json.default = JSON.parse(JSON.stringify(def.defaultValue));
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
+ if (value !== UNREPRESENTABLE_DEFAULT)
+ json.default = value;
}, prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
- if (ctx.io === "input")
- json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
+ if (ctx.io !== "input")
+ return;
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
+ if (value !== UNREPRESENTABLE_DEFAULT)
+ json._prefault = value;
}, catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(undefined);
} catch {
- throw new Error("Dynamic catch values are not supported in JSON Schema");
+ handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
+ return;
}
json.default = catchValue;
}, pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
- process3(innerType, ctx, params);
+ processSchema(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
}, readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
}, optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
- process3(def.innerType, ctx, params);
+ processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
var init_json_schema_processors = __esm(() => {
+ init_regexes();
+ init_schemas();
init_to_json_schema();
init_util();
+ contributors = {
+ greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
+ less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
+ multiple_of: (agg, def) => addDivisor(agg, def.value),
+ number_format: formatContributor(NUMBER_FORMAT_RANGES),
+ bigint_format: formatContributor(BIGINT_FORMAT_RANGES),
+ min_length: minContributor,
+ max_length: maxContributor,
+ length_equals: (agg, def) => narrowBoth(agg, def.length),
+ min_size: minContributor,
+ max_size: maxContributor,
+ size_equals: (agg, def) => narrowBoth(agg, def.size),
+ string_format: (agg, def) => {
+ setFormat(agg, def.format);
+ if (def.pattern)
+ addPattern(agg, def.pattern);
+ if (def.format === "base64" || def.format === "base64url")
+ agg.contentEncoding = def.format;
+ if (def.local || def.precision === -1)
+ agg.laxFormat = true;
+ },
+ mime_type: (agg, def) => intersectMime(agg, def.mime)
+ };
formatMap = {
guid: "uuid",
url: "uri",
@@ -71426,12 +72589,18 @@ var init_json_schema_processors = __esm(() => {
json_string: "json-string",
regex: ""
};
+ exactPatterns = new Map([
+ [base64Charset, base64],
+ [base64urlCharset, base64url]
+ ]);
+ pendingRecords = new WeakMap;
+ UNREPRESENTABLE_DEFAULT = Symbol();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/json-schema.js
var init_json_schema = () => {};
-// node_modules/.bun/[email protected]/node_modules/zod/v4/core/index.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/core/index.js
var init_core2 = __esm(() => {
init_util();
init_regexes();
@@ -71441,80 +72610,57 @@ var init_core2 = __esm(() => {
init_parse();
init_errors();
init_schemas();
+ init_memoizer();
init_checks();
init_versions();
init_registries();
+ init_compile();
init_api();
init_to_json_schema();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/checks.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/checks.js
var init_checks2 = __esm(() => {
init_core2();
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/iso.js
-function datetime2(params) {
- return _isoDateTime(ZodISODateTime, params);
-}
-function date2(params) {
- return _isoDate(ZodISODate, params);
-}
-function time2(params) {
- return _isoTime(ZodISOTime, params);
-}
-function duration2(params) {
- return _isoDuration(ZodISODuration, params);
-}
-var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration;
-var init_iso = __esm(() => {
- init_core2();
- init_schemas2();
- ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
- $ZodISODateTime.init(inst, def);
- ZodStringFormat.init(inst, def);
- });
- ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
- $ZodISODate.init(inst, def);
- ZodStringFormat.init(inst, def);
- });
- ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
- $ZodISOTime.init(inst, def);
- ZodStringFormat.init(inst, def);
- });
- ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
- $ZodISODuration.init(inst, def);
- ZodStringFormat.init(inst, def);
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/errors.js
+function _lazyMethod(proto, key, make) {
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const value = make(this);
+ Object.defineProperty(this, key, { value, configurable: true, writable: true });
+ return value;
+ },
+ set(value) {
+ Object.defineProperty(this, key, { value, configurable: true, writable: true });
+ }
});
-});
-
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/errors.js
-var initializer2 = (inst, issues) => {
+}
+var _installedErrorProtos, initializer2 = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
- Object.defineProperties(inst, {
- format: {
- value: (mapper) => formatError2(inst, mapper)
- },
- flatten: {
- value: (mapper) => flattenError(inst, mapper)
- },
- addIssue: {
- value: (issue) => {
- inst.issues.push(issue);
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
- }
- },
- addIssues: {
- value: (issues) => {
- inst.issues.push(...issues);
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
- }
- },
- isEmpty: {
- get() {
- return inst.issues.length === 0;
- }
+ const proto = Object.getPrototypeOf(inst);
+ if (_installedErrorProtos.has(proto))
+ return;
+ _installedErrorProtos.add(proto);
+ _lazyMethod(proto, "format", (self) => (mapper) => formatError2(self, mapper));
+ _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper));
+ _lazyMethod(proto, "addIssue", (self) => (issue) => {
+ self.issues.push(issue);
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
+ });
+ _lazyMethod(proto, "addIssues", (self) => (issues) => {
+ self.issues.push(...issues);
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
+ });
+ Object.defineProperty(proto, "isEmpty", {
+ configurable: true,
+ enumerable: false,
+ get() {
+ return this.issues.length === 0;
}
});
}, ZodRealError;
@@ -71522,20 +72668,22 @@ var init_errors2 = __esm(() => {
init_core2();
init_core2();
init_util();
- ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
+ _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
+ ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, undefined, {
Parent: Error
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/parse.js
-var parse5, parseAsync2, safeParse2, safeParseAsync2, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync;
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/parse.js
+var parse4, parseAsync, safeParse, safeParseAsync, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync;
var init_parse2 = __esm(() => {
init_core2();
init_errors2();
- parse5 = /* @__PURE__ */ _parse(ZodRealError);
- parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
- safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
- safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
+ init_core2();
+ parse4 = /* @__PURE__ */ _parse(ZodRealError);
+ parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
+ safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
+ safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
encode = /* @__PURE__ */ _encode(ZodRealError);
decode = /* @__PURE__ */ _decode(ZodRealError);
encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
@@ -71546,42 +72694,14 @@ var init_parse2 = __esm(() => {
safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/schemas.js
-function _installLazyMethods(inst, group, methods) {
- const proto = Object.getPrototypeOf(inst);
- let installed = _installedGroups.get(proto);
- if (!installed) {
- installed = new Set;
- _installedGroups.set(proto, installed);
- }
- if (installed.has(group))
- return;
- installed.add(group);
- for (const key in methods) {
- const fn = methods[key];
- Object.defineProperty(proto, key, {
- configurable: true,
- enumerable: false,
- get() {
- const bound = fn.bind(this);
- Object.defineProperty(this, key, {
- configurable: true,
- writable: true,
- enumerable: true,
- value: bound
- });
- return bound;
- },
- set(v) {
- Object.defineProperty(this, key, {
- configurable: true,
- writable: true,
- enumerable: true,
- value: v
- });
- }
- });
- }
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/schemas.js
+function _ensureDefaultLocale() {
+ if (!globalConfig.localeError)
+ config(en_default());
+}
+function _ensureDefaultMemoizer() {
+ if (!globalConfig.memoizer)
+ config({ memoizer: memoizer() });
}
function string2(params) {
return _string(ZodString, params);
@@ -71718,7 +72838,7 @@ function _catch(innerType, catchValue) {
return new ZodCatch({
type: "catch",
innerType,
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
+ catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
});
}
function pipe(in_, out) {
@@ -71747,236 +72867,344 @@ function preprocess(fn, schema) {
out: schema
});
}
-var _installedGroups, ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber, ZodNumberFormat, ZodBoolean, ZodUnknown, ZodNever, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodRecord, ZodEnum, ZodLiteral, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodCatch, ZodPipe, ZodPreprocess, ZodReadonly, ZodCustom;
+var ZodType, _ZodString, ZodString, ZodStringFormat, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber, ZodNumberFormat, ZodBoolean, ZodUnknown, ZodNever, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodRecord, ZodEnum, ZodLiteral, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodCatch, ZodPipe, ZodPreprocess, ZodReadonly, ZodCustom;
var init_schemas2 = __esm(() => {
init_core2();
init_core2();
init_json_schema_processors();
init_to_json_schema();
+ init_en();
init_checks2();
- init_iso();
init_parse2();
- _installedGroups = /* @__PURE__ */ new WeakMap;
ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
+ _ensureDefaultLocale();
$ZodType.init(inst, def);
- Object.assign(inst["~standard"], {
- jsonSchema: {
- input: createStandardJSONSchemaMethod(inst, "input"),
- output: createStandardJSONSchemaMethod(inst, "output")
- }
- });
- inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
inst.def = def;
inst.type = def.type;
- Object.defineProperty(inst, "_def", { value: def });
- inst.parse = (data, params) => parse5(inst, data, params, { callee: inst.parse });
- inst.safeParse = (data, params) => safeParse2(inst, data, params);
- inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
- inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
- inst.spa = inst.safeParseAsync;
- inst.encode = (data, params) => encode(inst, data, params);
- inst.decode = (data, params) => decode(inst, data, params);
- inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
- inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
- inst.safeEncode = (data, params) => safeEncode(inst, data, params);
- inst.safeDecode = (data, params) => safeDecode(inst, data, params);
- inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
- inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
- _installLazyMethods(inst, "ZodType", {
- check(...chks) {
- const def = this.def;
- return this.clone(mergeDefs(def, {
- checks: [
- ...def.checks ?? [],
- ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
- ]
- }), { parent: true });
- },
- with(...chks) {
- return this.check(...chks);
- },
- clone(def, params) {
- return clone(this, def, params);
- },
- brand() {
- return this;
- },
- register(reg, meta) {
- reg.add(this, meta);
- return this;
- },
- refine(check, params) {
- return this.check(refine(check, params));
- },
- superRefine(refinement, params) {
- return this.check(superRefine(refinement, params));
- },
- overwrite(fn) {
- return this.check(_overwrite(fn));
- },
- optional() {
- return optional(this);
- },
- exactOptional() {
- return exactOptional(this);
- },
- nullable() {
- return nullable(this);
- },
- nullish() {
- return optional(nullable(this));
- },
- nonoptional(params) {
- return nonoptional(this, params);
- },
- array() {
- return array(this);
- },
- or(arg) {
- return union([this, arg]);
- },
- and(arg) {
- return intersection(this, arg);
- },
- transform(tx) {
- return pipe(this, transform(tx));
- },
- default(d) {
- return _default(this, d);
- },
- prefault(d) {
- return prefault(this, d);
- },
- catch(params) {
- return _catch(this, params);
- },
- pipe(target) {
- return pipe(this, target);
- },
- readonly() {
- return readonly(this);
- },
- describe(description) {
- const cl = this.clone();
- globalRegistry.add(cl, { description });
- return cl;
- },
- meta(...args) {
- if (args.length === 0)
- return globalRegistry.get(this);
- const cl = this.clone();
- globalRegistry.add(cl, args[0]);
- return cl;
- },
- isOptional() {
- return this.safeParse(undefined).success;
- },
- isNullable() {
- return this.safeParse(null).success;
- },
- apply(fn) {
- return fn(this);
- }
- });
- Object.defineProperty(inst, "description", {
- get() {
- return globalRegistry.get(inst)?.description;
- },
- configurable: true
- });
return inst;
+ }, {
+ check(...chks) {
+ const def = this.def;
+ return this.clone(mergeDefs(def, {
+ checks: [
+ ...def.checks ?? [],
+ ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
+ ]
+ }), { parent: true });
+ },
+ with(...chks) {
+ return this.check(...chks);
+ },
+ clone(def, params) {
+ return clone(this, def, params);
+ },
+ brand() {
+ return this;
+ },
+ register(reg, meta) {
+ reg.add(this, meta);
+ return this;
+ },
+ refine(check, params) {
+ return this.check(refine(check, params));
+ },
+ superRefine(refinement, params) {
+ return this.check(superRefine(refinement, params));
+ },
+ overwrite(fn) {
+ return this.check(_overwrite(fn));
+ },
+ optional() {
+ return optional(this);
+ },
+ exactOptional() {
+ return exactOptional(this);
+ },
+ nullable() {
+ return nullable(this);
+ },
+ nullish() {
+ return optional(nullable(this));
+ },
+ nonoptional(params) {
+ return nonoptional(this, params);
+ },
+ array() {
+ return array(this);
+ },
+ or(arg) {
+ return union([this, arg]);
+ },
+ and(arg) {
+ return intersection(this, arg);
+ },
+ transform(tx) {
+ return pipe(this, transform(tx));
+ },
+ default(d) {
+ return _default(this, d);
+ },
+ prefault(d) {
+ return prefault(this, d);
+ },
+ catch(params) {
+ return _catch(this, params);
+ },
+ pipe(target) {
+ return pipe(this, target);
+ },
+ readonly() {
+ return readonly(this);
+ },
+ describe(description) {
+ const cl = this.clone();
+ globalRegistry.add(cl, { description });
+ return cl;
+ },
+ meta(...args) {
+ if (args.length === 0)
+ return globalRegistry.get(this);
+ const cl = this.clone();
+ globalRegistry.add(cl, args[0]);
+ return cl;
+ },
+ isOptional() {
+ return this.safeParse(undefined).success;
+ },
+ isNullable() {
+ return this.safeParse(null).success;
+ },
+ apply(fn, ...args) {
+ return args.length === 0 ? fn(this) : fn(this, ...args);
+ },
+ get "~standard"() {
+ return hide(this, "~standard", {
+ ...standardProps(this),
+ jsonSchema: {
+ input: createStandardJSONSchemaMethod(this, "input"),
+ output: createStandardJSONSchemaMethod(this, "output")
+ }
+ });
+ },
+ set "~standard"(value) {
+ own(this, "~standard", value);
+ },
+ parse: function _parse(data, params) {
+ return parse4(this, data, params, { callee: _parse });
+ },
+ parseAsync: async function _parseAsync(data, params) {
+ return await parseAsync(this, data, params, { callee: _parseAsync });
+ },
+ safeParse(data, params) {
+ return safeParse(this, data, params);
+ },
+ async safeParseAsync(data, params) {
+ return safeParseAsync(this, data, params);
+ },
+ get spa() {
+ return this?.safeParseAsync;
+ },
+ set spa(value) {
+ own(this, "spa", value);
+ },
+ validate(data, params) {
+ return validate(this, data, params);
+ },
+ validateAsync(data, params) {
+ return validateAsync(this, data, params);
+ },
+ encode: function _encode(data, params) {
+ return encode(this, data, params, { callee: _encode });
+ },
+ decode: function _decode(data, params) {
+ return decode(this, data, params, { callee: _decode });
+ },
+ encodeAsync: async function _encodeAsync(data, params) {
+ return await encodeAsync(this, data, params, { callee: _encodeAsync });
+ },
+ decodeAsync: async function _decodeAsync(data, params) {
+ return await decodeAsync(this, data, params, { callee: _decodeAsync });
+ },
+ safeEncode(data, params) {
+ return safeEncode(this, data, params);
+ },
+ safeDecode(data, params) {
+ return safeDecode(this, data, params);
+ },
+ async safeEncodeAsync(data, params) {
+ return safeEncodeAsync(this, data, params);
+ },
+ async safeDecodeAsync(data, params) {
+ return safeDecodeAsync(this, data, params);
+ },
+ toJSONSchema(params) {
+ return createToJSONSchemaMethod(this, {})(params);
+ },
+ get description() {
+ return globalRegistry.get(this)?.description;
+ },
+ get _def() {
+ return this._zod.def;
+ }
});
_ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
- const bag = inst._zod.bag;
- inst.format = bag.format ?? null;
- inst.minLength = bag.minimum ?? null;
- inst.maxLength = bag.maximum ?? null;
- _installLazyMethods(inst, "_ZodString", {
- regex(...args) {
- return this.check(_regex(...args));
- },
- includes(...args) {
- return this.check(_includes(...args));
- },
- startsWith(...args) {
- return this.check(_startsWith(...args));
- },
- endsWith(...args) {
- return this.check(_endsWith(...args));
- },
- min(...args) {
- return this.check(_minLength(...args));
- },
- max(...args) {
- return this.check(_maxLength(...args));
- },
- length(...args) {
- return this.check(_length(...args));
- },
- nonempty(...args) {
- return this.check(_minLength(1, ...args));
- },
- lowercase(params) {
- return this.check(_lowercase(params));
- },
- uppercase(params) {
- return this.check(_uppercase(params));
- },
- trim() {
- return this.check(_trim());
- },
- normalize(...args) {
- return this.check(_normalize(...args));
- },
- toLowerCase() {
- return this.check(_toLowerCase());
- },
- toUpperCase() {
- return this.check(_toUpperCase());
- },
- slugify() {
- return this.check(_slugify());
- }
- });
- });
+ }, /* @__PURE__ */ derived({
+ format: (inst) => aggregateChecks(inst).format ?? null,
+ minLength: (inst) => aggregateChecks(inst).minimum ?? null,
+ maxLength: (inst) => aggregateChecks(inst).maximum ?? null
+ }, {
+ regex(...args) {
+ return this.check(_regex(...args));
+ },
+ includes(...args) {
+ return this.check(_includes(...args));
+ },
+ startsWith(...args) {
+ return this.check(_startsWith(...args));
+ },
+ endsWith(...args) {
+ return this.check(_endsWith(...args));
+ },
+ min(...args) {
+ return this.check(_minLength(...args));
+ },
+ max(...args) {
+ return this.check(_maxLength(...args));
+ },
+ length(...args) {
+ return this.check(_length(...args));
+ },
+ nonempty(...args) {
+ return this.check(_minLength(1, ...args));
+ },
+ lowercase(params) {
+ return this.check(_lowercase(params));
+ },
+ uppercase(params) {
+ return this.check(_uppercase(params));
+ },
+ trim() {
+ return this.check(_trim());
+ },
+ normalize(...args) {
+ return this.check(_normalize(...args));
+ },
+ toLowerCase() {
+ return this.check(_toLowerCase());
+ },
+ toUpperCase() {
+ return this.check(_toUpperCase());
+ },
+ slugify() {
+ return this.check(_slugify());
+ }
+ }));
ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
$ZodString.init(inst, def);
_ZodString.init(inst, def);
- inst.email = (params) => inst.check(_email(ZodEmail, params));
- inst.url = (params) => inst.check(_url(ZodURL, params));
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
- inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
- inst.datetime = (params) => inst.check(datetime2(params));
- inst.date = (params) => inst.check(date2(params));
- inst.time = (params) => inst.check(time2(params));
- inst.duration = (params) => inst.check(duration2(params));
+ }, {
+ email(params) {
+ return this.check(_email(ZodEmail, params));
+ },
+ url(params) {
+ return this.check(_url(ZodURL, params));
+ },
+ jwt(params) {
+ return this.check(_jwt(ZodJWT, params));
+ },
+ emoji(params) {
+ return this.check(_emoji2(ZodEmoji, params));
+ },
+ guid(params) {
+ return this.check(_guid(ZodGUID, params));
+ },
+ uuid(params) {
+ return this.check(_uuid(ZodUUID, params));
+ },
+ uuidv4(params) {
+ return this.check(_uuidv4(ZodUUID, params));
+ },
+ uuidv6(params) {
+ return this.check(_uuidv6(ZodUUID, params));
+ },
+ uuidv7(params) {
+ return this.check(_uuidv7(ZodUUID, params));
+ },
+ nanoid(params) {
+ return this.check(_nanoid(ZodNanoID, params));
+ },
+ cuid(params) {
+ return this.check(_cuid(ZodCUID, params));
+ },
+ cuid2(params) {
+ return this.check(_cuid2(ZodCUID2, params));
+ },
+ ulid(params) {
+ return this.check(_ulid(ZodULID, params));
+ },
+ base64(params) {
+ return this.check(_base64(ZodBase64, params));
+ },
+ base64url(params) {
+ return this.check(_base64url(ZodBase64URL, params));
+ },
+ xid(params) {
+ return this.check(_xid(ZodXID, params));
+ },
+ ksuid(params) {
+ return this.check(_ksuid(ZodKSUID, params));
+ },
+ ipv4(params) {
+ return this.check(_ipv4(ZodIPv4, params));
+ },
+ ipv6(params) {
+ return this.check(_ipv6(ZodIPv6, params));
+ },
+ cidrv4(params) {
+ return this.check(_cidrv4(ZodCIDRv4, params));
+ },
+ cidrv6(params) {
+ return this.check(_cidrv6(ZodCIDRv6, params));
+ },
+ e164(params) {
+ return this.check(_e164(ZodE164, params));
+ },
+ datetime(params) {
+ return this.check(_isoDateTime(ZodISODateTime, params));
+ },
+ date(params) {
+ return this.check(_isoDate(ZodISODate, params));
+ },
+ time(params) {
+ return this.check(_isoTime(ZodISOTime, params));
+ },
+ duration(params) {
+ return this.check(_isoDuration(ZodISODuration, params));
+ }
});
ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
+ ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
+ $ZodISODateTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
+ ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
+ $ZodISODate.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
+ ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
+ $ZodISOTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
+ ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
+ $ZodISODuration.init(inst, def);
+ ZodStringFormat.init(inst, def);
+ });
ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
@@ -72057,60 +73285,68 @@ var init_schemas2 = __esm(() => {
$ZodNumber.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
- _installLazyMethods(inst, "ZodNumber", {
- gt(value, params) {
- return this.check(_gt(value, params));
- },
- gte(value, params) {
- return this.check(_gte(value, params));
- },
- min(value, params) {
- return this.check(_gte(value, params));
- },
- lt(value, params) {
- return this.check(_lt(value, params));
- },
- lte(value, params) {
- return this.check(_lte(value, params));
- },
- max(value, params) {
- return this.check(_lte(value, params));
- },
- int(params) {
- return this.check(int(params));
- },
- safe(params) {
- return this.check(int(params));
- },
- positive(params) {
- return this.check(_gt(0, params));
- },
- nonnegative(params) {
- return this.check(_gte(0, params));
- },
- negative(params) {
- return this.check(_lt(0, params));
- },
- nonpositive(params) {
- return this.check(_lte(0, params));
- },
- multipleOf(value, params) {
- return this.check(_multipleOf(value, params));
- },
- step(value, params) {
- return this.check(_multipleOf(value, params));
- },
- finite() {
- return this;
- }
- });
- const bag = inst._zod.bag;
- inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
- inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
- inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
inst.isFinite = true;
- inst.format = bag.format ?? null;
- });
+ }, /* @__PURE__ */ derived({
+ minValue: (inst) => {
+ const { minimum, exclusiveMinimum } = aggregateChecks(inst);
+ return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);
+ },
+ maxValue: (inst) => {
+ const { maximum, exclusiveMaximum } = aggregateChecks(inst);
+ return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);
+ },
+ isInt: (inst) => {
+ const { isInt, multipleOf } = aggregateChecks(inst);
+ return !!isInt || !!multipleOf?.some(Number.isSafeInteger);
+ },
+ format: (inst) => aggregateChecks(inst).format ?? null
+ }, {
+ gt(value, params) {
+ return this.check(_gt(value, params));
+ },
+ gte(value, params) {
+ return this.check(_gte(value, params));
+ },
+ min(value, params) {
+ return this.check(_gte(value, params));
+ },
+ lt(value, params) {
+ return this.check(_lt(value, params));
+ },
+ lte(value, params) {
+ return this.check(_lte(value, params));
+ },
+ max(value, params) {
+ return this.check(_lte(value, params));
+ },
+ int(params) {
+ return this.check(int(params));
+ },
+ safe(params) {
+ return this.check(int(params));
+ },
+ positive(params) {
+ return this.check(_gt(0, params));
+ },
+ nonnegative(params) {
+ return this.check(_gte(0, params));
+ },
+ negative(params) {
+ return this.check(_lt(0, params));
+ },
+ nonpositive(params) {
+ return this.check(_lte(0, params));
+ },
+ multipleOf(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ step(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ finite() {
+ return this;
+ }
+ }));
ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
$ZodNumberFormat.init(inst, def);
ZodNumber.init(inst, def);
@@ -72131,76 +73367,77 @@ var init_schemas2 = __esm(() => {
inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
});
ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodArray.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
- _installLazyMethods(inst, "ZodArray", {
- min(n, params) {
- return this.check(_minLength(n, params));
- },
- nonempty(params) {
- return this.check(_minLength(1, params));
- },
- max(n, params) {
- return this.check(_maxLength(n, params));
- },
- length(n, params) {
- return this.check(_length(n, params));
- },
- unwrap() {
- return this.element;
- }
- });
+ }, {
+ min(n, params) {
+ return this.check(_minLength(n, params));
+ },
+ nonempty(params) {
+ return this.check(_minLength(1, params));
+ },
+ max(n, params) {
+ return this.check(_maxLength(n, params));
+ },
+ length(n, params) {
+ return this.check(_length(n, params));
+ },
+ unwrap() {
+ return this.element;
+ }
});
ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodObjectJIT.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
- defineLazy(inst, "shape", () => {
- return def.shape;
- });
- _installLazyMethods(inst, "ZodObject", {
- keyof() {
- return _enum(Object.keys(this._zod.def.shape));
- },
- catchall(catchall) {
- return this.clone({ ...this._zod.def, catchall });
- },
- passthrough() {
- return this.clone({ ...this._zod.def, catchall: unknown() });
- },
- loose() {
- return this.clone({ ...this._zod.def, catchall: unknown() });
- },
- strict() {
- return this.clone({ ...this._zod.def, catchall: never() });
- },
- strip() {
- return this.clone({ ...this._zod.def, catchall: undefined });
- },
- extend(incoming) {
- return extend(this, incoming);
- },
- safeExtend(incoming) {
- return safeExtend(this, incoming);
- },
- merge(other) {
- return merge(this, other);
- },
- pick(mask) {
- return pick3(this, mask);
- },
- omit(mask) {
- return omit(this, mask);
- },
- partial(...args) {
- return partial(ZodOptional, this, args[0]);
- },
- required(...args) {
- return required(ZodNonOptional, this, args[0]);
- }
- });
+ installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
+ }, {
+ keyof() {
+ return _enum(Object.keys(this._zod.def.shape));
+ },
+ catchall(catchall) {
+ return this.clone(mergeDefs(this._zod.def, { catchall }));
+ },
+ passthrough() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
+ },
+ loose() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
+ },
+ strict() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: never() }));
+ },
+ strip() {
+ return this.clone(mergeDefs(this._zod.def, { catchall: undefined }));
+ },
+ extend(incoming) {
+ return extend(this, incoming);
+ },
+ safeExtend(incoming) {
+ return safeExtend(this, incoming);
+ },
+ merge(other) {
+ return merge(this, other);
+ },
+ pick(mask) {
+ return pick3(this, mask);
+ },
+ omit(mask) {
+ return omit(this, mask);
+ },
+ partial(...args) {
+ return partial(ZodOptional, this, args[0]);
+ },
+ exactPartial(...args) {
+ return partial(ZodExactOptional, this, args[0], "exactPartial");
+ },
+ required(...args) {
+ return required(ZodNonOptional, this, args[0]);
+ }
});
ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
$ZodUnion.init(inst, def);
@@ -72218,6 +73455,7 @@ var init_schemas2 = __esm(() => {
inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
});
ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodRecord.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
@@ -72229,7 +73467,7 @@ var init_schemas2 = __esm(() => {
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
inst.enum = def.entries;
- inst.options = Object.values(def.entries);
+ inst.options = [...inst._zod.values];
const keys = new Set(Object.keys(def.entries));
inst.extract = (values, params) => {
const newEntries = {};
@@ -72277,6 +73515,7 @@ var init_schemas2 = __esm(() => {
});
});
ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
+ _ensureDefaultMemoizer();
$ZodTransform.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
@@ -72292,7 +73531,8 @@ var init_schemas2 = __esm(() => {
if (_issue.fatal)
_issue.continue = false;
_issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
+ if (!("input" in _issue))
+ _issue.input = payload.value;
_issue.inst ?? (_issue.inst = inst);
payload.issues.push(issue(_issue));
}
@@ -72301,12 +73541,10 @@ var init_schemas2 = __esm(() => {
if (output instanceof Promise) {
return output.then((output) => {
payload.value = output;
- payload.fallback = true;
return payload;
});
}
payload.value = output;
- payload.fallback = true;
return payload;
};
});
@@ -72378,20 +73616,21 @@ var init_schemas2 = __esm(() => {
});
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/compat.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/compat.js
var ZodFirstPartyTypeKind;
var init_compat = __esm(() => {
(function(ZodFirstPartyTypeKind) {})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
});
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/coerce.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/iso.js
+var init_iso = () => {};
+
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/coerce.js
var init_coerce = () => {};
-// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/external.js
+// node_modules/.bun/[email protected]/node_modules/zod/v4/classic/external.js
var init_external = __esm(() => {
init_core2();
- init_core2();
- init_en();
init_locales();
init_iso();
init_coerce();
@@ -72400,10 +73639,9 @@ var init_external = __esm(() => {
init_errors2();
init_parse2();
init_compat();
- config(en_default());
});
-// node_modules/.bun/[email protected]/node_modules/zod/index.js
+// node_modules/.bun/[email protected]/node_modules/zod/index.js
var init_zod = __esm(() => {
init_external();
init_external();
@@ -77365,7 +78603,7 @@ var init_env = __esm(() => {
SEND_OPT_OUT_VALUES = ["0", "false", "no", "yes"];
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
import { dirname as dirname17, posix as posix7, sep as sep7 } from "path";
function createModulerModifier() {
const getModuleFromFileName = createGetModuleFromFilename();
@@ -77402,136 +78640,7 @@ function normalizeWindowsPath(path) {
}
var init_module_node = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
-function getFlagDetailFromFlagAndPayload(key, value, payload) {
- return {
- key,
- enabled: typeof value == "string" ? true : value,
- variant: typeof value == "string" ? value : undefined,
- reason: undefined,
- metadata: {
- id: undefined,
- version: undefined,
- payload: payload ? JSON.stringify(payload) : undefined,
- description: undefined
- }
- };
-}
-var normalizeFlagsResponse = (flagsResponse) => {
- if ("flags" in flagsResponse) {
- const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
- const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads
- };
- }
- {
- const featureFlags = flagsResponse.featureFlags ?? {};
- const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
- k,
- parsePayload(v)
- ]));
- const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
- key,
- getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
- ]));
- return {
- ...flagsResponse,
- featureFlags,
- featureFlagPayloads,
- flags
- };
- }
-}, getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
- key,
- getFeatureFlagValue(detail)
-]).filter(([, value]) => value !== undefined)), getPayloadsFromFlags = (flags) => {
- const safeFlags = flags ?? {};
- return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
- const details = safeFlags[flag];
- return details.enabled && details.metadata && details.metadata.payload !== undefined;
- }).map((flag) => {
- const payload = safeFlags[flag].metadata?.payload;
- return [
- flag,
- payload ? parsePayload(payload) : undefined
- ];
- }));
-}, getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled, parsePayload = (response) => {
- if (typeof response != "string")
- return response;
- try {
- return JSON.parse(response);
- } catch {
- return response;
- }
-}, MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
- const minimal = {};
- const copyKey = (key) => {
- if (properties[key] !== undefined)
- minimal[key] = properties[key];
- };
- MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
- transportKeys.forEach(copyKey);
- return minimal;
-};
-var init_featureFlagUtils = __esm(() => {
- MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
- "utm_source",
- "utm_medium",
- "utm_campaign",
- "utm_content",
- "utm_term",
- "gad_source",
- "mc_cid",
- "gclid",
- "gclsrc",
- "dclid",
- "gbraid",
- "wbraid",
- "fbclid",
- "msclkid",
- "twclid",
- "li_fat_id",
- "igshid",
- "ttclid",
- "rdt_cid",
- "epik",
- "qclid",
- "sccid",
- "irclid",
- "_kx"
- ];
- MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
- "$feature_flag",
- "$feature_flag_response",
- "$feature_flag_has_experiment",
- "$feature_flag_id",
- "$feature_flag_version",
- "$feature_flag_reason",
- "$feature_flag_request_id",
- "$feature_flag_evaluated_at",
- "$feature_flag_error",
- "locally_evaluated",
- "$groups",
- "$process_person_profile",
- "$geoip_disable",
- "$current_url",
- "$pathname",
- "$referring_domain",
- ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
- "$session_id",
- "$window_id",
- "$lib",
- "$lib_version",
- "$device_id",
- "$is_server"
- ];
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/types.mjs
var types_PostHogPersistedProperty;
var init_types7 = __esm(() => {
types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
@@ -77563,6 +78672,7 @@ var init_types7 = __esm(() => {
PostHogPersistedProperty["PushRegistered"] = "push_registered";
PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
+ PostHogPersistedProperty["SurveysInProgress"] = "surveys_in_progress";
PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
PostHogPersistedProperty["Surveys"] = "surveys";
PostHogPersistedProperty["RemoteConfig"] = "remote_config";
@@ -77572,98 +78682,78 @@ var init_types7 = __esm(() => {
}({});
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
-function isGzipSupported() {
- return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
+function safeJsonStringify(value) {
+ const ancestors = [];
+ return JSON.stringify(value, function(_key, replacementValue) {
+ if (typeof replacementValue == "bigint")
+ return replacementValue.toString();
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
+ return;
+ if (replacementValue instanceof Error)
+ return {
+ name: replacementValue.name,
+ message: replacementValue.message,
+ stack: replacementValue.stack
+ };
+ if (replacementValue && typeof replacementValue == "object") {
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
+ ancestors.pop();
+ if (ancestors.includes(replacementValue))
+ return "[Circular]";
+ ancestors.push(replacementValue);
+ }
+ return replacementValue;
+ }) ?? "null";
}
-async function gzipCompress(input, isDebug = true, options) {
- try {
- const inputBytes = new TextEncoder().encode(input);
- const compressedStream = new globalThis.CompressionStream("gzip");
- const writer = compressedStream.writable.getWriter();
- const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
- try {
- await writer.abort(err);
- } catch {}
- throw err;
- });
- const responsePromise = new Response(compressedStream.readable).blob();
- const [compressed] = await Promise.all([
- responsePromise,
- writePromise
- ]);
- await validateNativeGzip(compressed, inputBytes);
- return compressed;
- } catch (error) {
- if (options?.rethrow)
- throw error;
- if (isDebug)
- console.error("Failed to gzip compress data", error);
- return null;
- }
+var init_string_utils = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
+function isPrimitive(value) {
+ return value === null || typeof value != "object";
}
-var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError", GZIP_MAGIC_FIRST_BYTE = 31, GZIP_MAGIC_SECOND_BYTE = 139, GZIP_DEFLATE_METHOD = 8, hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE, crc32Table, getCrc32Table = () => {
- if (crc32Table)
- return crc32Table;
- crc32Table = [];
- for (let i = 0;i < 256; i++) {
- let crc = i;
- for (let j = 0;j < 8; j++)
- crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
- crc32Table[i] = crc >>> 0;
+function isBuiltin(candidate, className) {
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
+}
+function isError(candidate) {
+ switch (Object.prototype.toString.call(candidate)) {
+ case "[object Error]":
+ case "[object Exception]":
+ case "[object DOMException]":
+ case "[object DOMError]":
+ case "[object WebAssembly.Exception]":
+ return true;
+ default:
+ return isInstanceOf(candidate, Error);
}
- return crc32Table;
-}, crc32 = (bytes) => {
- const table = getCrc32Table();
- let crc = 4294967295;
- for (let i = 0;i < bytes.length; i++)
- crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
- return (4294967295 ^ crc) >>> 0;
-}, throwNativeGzipValidationError = (reason) => {
- const error = new Error(`Native gzip produced invalid output: ${reason}`);
- error.name = NATIVE_GZIP_VALIDATION_ERROR;
- throw error;
-}, validateNativeGzip = async (compressed, inputBytes) => {
- if (compressed.size < 18)
- throwNativeGzipValidationError("too-short");
- const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
- if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
- throwNativeGzipValidationError("invalid-header");
- const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
- if (trailer.getUint32(0, true) !== crc32(inputBytes))
- throwNativeGzipValidationError("invalid-crc");
- const inputSize = inputBytes.length >>> 0;
- if (trailer.getUint32(4, true) !== inputSize)
- throwNativeGzipValidationError("invalid-size");
-};
-var init_gzip = __esm(() => {
- init_types7();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
-function sanitizeString(value) {
- let output = "";
- for (let index = 0;index < value.length; index++) {
- const codeUnit = value.charCodeAt(index);
- if (codeUnit >= 55296 && codeUnit <= 56319) {
- const nextCodeUnit = value.charCodeAt(index + 1);
- if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
- output += value[index] + value[index + 1];
- index++;
- } else
- output += "\uFFFD";
- } else
- output += codeUnit >= 56320 && codeUnit <= 57343 ? "\uFFFD" : value[index];
+}
+function isEvent(candidate) {
+ return "u" > typeof Event && isInstanceOf(candidate, Event);
+}
+function isPlainObject6(candidate) {
+ return isBuiltin(candidate, "Object");
+}
+function isInstanceOf(candidate, base) {
+ try {
+ return candidate instanceof base;
+ } catch {
+ return false;
}
- return output;
}
-var MAX_JSON_SAFE_VALUE_DEPTH = 20, MAX_JSON_SAFE_VALUE_ITEMS = 1000, MAX_JSON_SAFE_VALUE_NODES = 1e4, CIRCULAR_VALUE = "[Circular]", TRUNCATED_VALUE = "[Truncated]", UNSERIALIZABLE_VALUE = "[Unserializable]", FUNCTION_VALUE = "[Function]", dateGetTime, dateToISOString;
-var init_json_utils = __esm(() => {
- dateGetTime = Date.prototype.getTime;
- dateToISOString = Date.prototype.toISOString;
+var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject2 = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNull = (x) => x === null, isNullish = (x) => isUndefined(x) || isNull(x), isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
+var init_type_utils = __esm(() => {
+ init_types7();
+ init_string_utils();
+ nativeIsArray = Array.isArray;
+ ObjProto = Object.prototype;
+ type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
+ type_utils_toString = ObjProto.toString;
+ isArray = nativeIsArray || function(obj) {
+ return type_utils_toString.call(obj) === "[object Array]";
+ };
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bot-detection.mjs
var DEFAULT_BLOCKED_UA_STRS, isBlockedUA = function(ua, customBlockedUserAgents = []) {
if (!ua)
return false;
@@ -77701,7 +78791,7 @@ var init_bot_detection = __esm(() => {
"msnbot",
"nessus",
"petalbot",
- "pinterest",
+ "pinterestbot",
"prerender",
"rogerbot",
"screaming frog",
@@ -77755,83 +78845,12 @@ var init_bot_detection = __esm(() => {
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/string-utils.mjs
-function safeJsonStringify(value) {
- const ancestors = [];
- return JSON.stringify(value, function(_key, replacementValue) {
- if (typeof replacementValue == "bigint")
- return replacementValue.toString();
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
- return;
- if (replacementValue instanceof Error)
- return {
- name: replacementValue.name,
- message: replacementValue.message,
- stack: replacementValue.stack
- };
- if (replacementValue && typeof replacementValue == "object") {
- while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
- ancestors.pop();
- if (ancestors.includes(replacementValue))
- return "[Circular]";
- ancestors.push(replacementValue);
- }
- return replacementValue;
- }) ?? "null";
-}
-var init_string_utils = () => {};
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/browser-utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/browser-utils.mjs
var init_browser_utils = __esm(() => {
init_string_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/type-utils.mjs
-function isPrimitive(value) {
- return value === null || typeof value != "object";
-}
-function isBuiltin(candidate, className) {
- return Object.prototype.toString.call(candidate) === `[object ${className}]`;
-}
-function isError(candidate) {
- switch (Object.prototype.toString.call(candidate)) {
- case "[object Error]":
- case "[object Exception]":
- case "[object DOMException]":
- case "[object DOMError]":
- case "[object WebAssembly.Exception]":
- return true;
- default:
- return isInstanceOf(candidate, Error);
- }
-}
-function isEvent(candidate) {
- return typeof Event != "undefined" && isInstanceOf(candidate, Event);
-}
-function isPlainObject6(candidate) {
- return isBuiltin(candidate, "Object");
-}
-function isInstanceOf(candidate, base) {
- try {
- return candidate instanceof base;
- } catch {
- return false;
- }
-}
-var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject2 = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNull = (x) => x === null, isNullish = (x) => isUndefined(x) || isNull(x), isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
-var init_type_utils = __esm(() => {
- init_types7();
- init_string_utils();
- nativeIsArray = Array.isArray;
- ObjProto = Object.prototype;
- type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
- type_utils_toString = ObjProto.toString;
- isArray = nativeIsArray || function(obj) {
- return type_utils_toString.call(obj) === "[object Array]";
- };
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/number-utils.mjs
function clampToRange(value, min, max, logger, fallbackValue) {
if (min > max) {
logger.warn("min cannot be greater than max.");
@@ -77848,13 +78867,13 @@ function clampToRange(value, min, max, logger, fallbackValue) {
return min;
}
logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
- return clampToRange(fallbackValue || max, min, max, logger);
+ return clampToRange(fallbackValue ?? max, min, max, logger);
}
var init_number_utils = __esm(() => {
init_type_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
function resolveExceptionRateLimiterConfig(config = {}) {
return {
refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,
@@ -77908,7 +78927,7 @@ var init_bucketed_rate_limiter = __esm(() => {
init_number_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
class UUID {
constructor(bytes) {
this.bytes = bytes;
@@ -78077,13 +79096,13 @@ class V7Generator {
}
}
var DIGITS = "0123456789abcdef", getDefaultRandom = () => ({
- nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random()) >>> 0
}), defaultGenerator, uuidv7 = () => uuidv7obj().toString(), uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
var init_uuidv7 = __esm(() => {
- /*! For license information please see uuidv7.mjs.LICENSE.txt */
+ /*! LICENSE: uuidv7.mjs.LICENSE.txt */
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/promise-queue.mjs
class PromiseQueue {
add(promise) {
const promiseUUID = uuidv7();
@@ -78125,7 +79144,7 @@ var init_promise_queue = __esm(() => {
init_uuidv7();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/logger.mjs
function createConsole(consoleLike = console) {
const lockedMethods = {
log: consoleLike.log.bind(consoleLike),
@@ -78167,8 +79186,8 @@ var _createLogger = (prefix, maybeCall, consoleLike) => {
}, passThrough = (fn) => fn();
var init_logger4 = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
-var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", GOOGLE_SEARCH_APP = "Google Search App", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
+var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", CLAUDE = "Claude", CODEX = "Codex", CHATGPT = "ChatGPT", GOOGLE_SEARCH_APP = "Google Search App", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, AI_APP_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
var init_user_agent_utils = __esm(() => {
init_string_utils();
init_type_utils();
@@ -78188,6 +79207,7 @@ var init_user_agent_utils = __esm(() => {
GENERIC_MOBILE = GENERIC + " " + MOBILE.toLowerCase();
GENERIC_TABLET = GENERIC + " " + TABLET.toLowerCase();
DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
+ AI_APP_VERSION_REGEX = new RegExp("(" + CLAUDE + "|" + CODEX + "|" + CHATGPT + ")\\/" + BROWSER_VERSION_REGEX_SUFFIX);
XBOX_REGEX = new RegExp(XBOX, "i");
PLAYSTATION_REGEX = new RegExp(PLAYSTATION + " \\w+", "i");
NINTENDO_REGEX = new RegExp(NINTENDO + " \\w+", "i");
@@ -78264,6 +79284,15 @@ var init_user_agent_utils = __esm(() => {
[BRAVE]: [
new RegExp(BRAVE + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
+ [CLAUDE]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CODEX]: [
+ AI_APP_VERSION_REGEX
+ ],
+ [CHATGPT]: [
+ AI_APP_VERSION_REGEX
+ ],
[DUCKDUCKGO]: [
new RegExp("(DuckDuckGo|Ddg)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
],
@@ -78436,13 +79465,139 @@ var init_user_agent_utils = __esm(() => {
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/webview-app-utils.mjs
+var init_webview_app_utils = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/json-utils.mjs
+function sanitizeString(value) {
+ let output = "";
+ for (let index = 0;index < value.length; index++) {
+ const codeUnit = value.charCodeAt(index);
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
+ const nextCodeUnit = value.charCodeAt(index + 1);
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
+ output += value[index] + value[index + 1];
+ index++;
+ } else
+ output += "\uFFFD";
+ } else
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "\uFFFD" : value[index];
+ }
+ return output;
+}
+function assignUserAttributes(target, source) {
+ if (!source)
+ return target;
+ let keys = [];
+ try {
+ keys = Object.keys(source);
+ } catch {
+ keys = [];
+ }
+ for (const key of keys) {
+ let value;
+ try {
+ value = source[key];
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ return target;
+}
+var MAX_JSON_SAFE_VALUE_DEPTH = 20, MAX_JSON_SAFE_VALUE_ITEMS = 1000, MAX_JSON_SAFE_VALUE_NODES = 1e4, CIRCULAR_VALUE = "[Circular]", TRUNCATED_VALUE = "[Truncated]", UNSERIALIZABLE_VALUE = "[Unserializable]", FUNCTION_VALUE = "[Function]", dateGetTime, dateToISOString;
+var init_json_utils = __esm(() => {
+ dateGetTime = Date.prototype.getTime;
+ dateToISOString = Date.prototype.toISOString;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/retry-after.mjs
+function parseRetryAfterMs(value, now = Date.now()) {
+ if (typeof value != "string" || !value)
+ return;
+ const raw = value.trim();
+ const trimmed = /^\d+\s*,/.test(raw) ? raw.slice(0, raw.indexOf(",")).trim() : raw;
+ if (/^\d+$/.test(trimmed)) {
+ const ms = 1000 * Math.min(Number(trimmed), MAX_RETRY_AFTER_MS / 1000);
+ return ms > 0 ? ms : undefined;
+ }
+ if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(trimmed))
+ return;
+ const date = /^\w{3} \w{3} /.test(trimmed) ? trimmed + " GMT" : trimmed;
+ const ms = Date.parse(date) - now;
+ if (!Number.isFinite(ms) || ms <= 0)
+ return;
+ return Math.min(ms, MAX_RETRY_AFTER_MS);
+}
+
+class RetryAfterWindow {
+ record(outcome) {
+ if (outcome.kind === "too-large")
+ return;
+ if (outcome.kind !== "retry-later")
+ return void this.reset();
+ if (!outcome.retryAfterMs)
+ return;
+ const open = this.isOpen();
+ const now = Date.now();
+ const asked = Math.min(outcome.retryAfterMs, MAX_RETRY_AFTER_MS);
+ if (!open) {
+ this._installedAt = now;
+ this._until = now + asked;
+ return;
+ }
+ this._until = Math.max(this._until, Math.min(now + asked, this._installedAt + MAX_RETRY_AFTER_MS));
+ }
+ remainingMs() {
+ const now = Date.now();
+ if (now < this._installedAt - CLOCK_STEP_TOLERANCE_MS) {
+ this.reset();
+ return 0;
+ }
+ const remaining = Math.min(MAX_RETRY_AFTER_MS, Math.max(0, this._until - now));
+ if (remaining === 0)
+ this.reset();
+ return remaining;
+ }
+ isOpen() {
+ return this.remainingMs() > 0;
+ }
+ reset() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+ constructor() {
+ this._until = 0;
+ this._installedAt = 0;
+ }
+}
+var MAX_RETRY_AFTER_MS = 300000, CLOCK_STEP_TOLERANCE_MS = 5000;
+var init_retry_after = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/index.mjs
function isValidUUID(value) {
return typeof value == "string" && UUID_REGEX.test(value);
}
function getEventUuid(uuid, generateUuid) {
return isValidUUID(uuid) ? uuid : generateUuid();
}
+function createNamedError(name, message) {
+ const error = new Error(message);
+ try {
+ Object.defineProperty(error, "name", {
+ value: name,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ } catch {}
+ return error;
+}
function removeTrailingSlash(url) {
return url?.replace(/\/+$/, "");
}
@@ -78499,9 +79654,11 @@ function allSettled(promises) {
reason
}))));
}
-var STRING_FORMAT = "utf8", UUID_REGEX;
+var STRING_FORMAT = "utf8", UUID_REGEX, isPromise = (obj) => obj && typeof obj.then == "function";
var init_utils = __esm(() => {
+ init_type_utils();
init_json_utils();
+ init_retry_after();
init_bot_detection();
init_browser_utils();
init_bucketed_rate_limiter();
@@ -78511,902 +79668,380 @@ var init_utils = __esm(() => {
init_promise_queue();
init_logger4();
init_user_agent_utils();
+ init_webview_app_utils();
UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
-function newState() {
- return {
- ancestors: new WeakSet,
- remainingNodes: MAX_JSON_SAFE_VALUE_NODES
- };
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
+function getFilenameToChunkIdMap(stackParser) {
+ const chunkIdMap = globalThis._posthogChunkIds;
+ if (!chunkIdMap)
+ return;
+ const chunkIdKeys = Object.keys(chunkIdMap);
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
+ return cachedFilenameChunkIds;
+ lastKeysCount = chunkIdKeys.length;
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
+ if (!parsedStackResults)
+ parsedStackResults = {};
+ const result = parsedStackResults[stackKey];
+ if (result)
+ acc[result[0]] = result[1];
+ else {
+ const parsedStack = stackParser(stackKey);
+ for (let i = parsedStack.length - 1;i >= 0; i--) {
+ const stackFrame = parsedStack[i];
+ const filename = stackFrame?.filename;
+ const chunkId = chunkIdMap[stackKey];
+ if (filename && chunkId) {
+ acc[filename] = chunkId;
+ parsedStackResults[stackKey] = [
+ filename,
+ chunkId
+ ];
+ break;
+ }
+ }
+ }
+ return acc;
+ }, {});
+ return cachedFilenameChunkIds;
}
-function toOtlpKeyValueList(attrs, logger) {
- try {
- return encodeKeyValueList(attrs, logger, newState(), 0);
- } catch {
- return [];
+var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
+var init_chunk_ids = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
+class ErrorPropertiesBuilder {
+ constructor(coercers, stackParser, modifiers = []) {
+ this.coercers = coercers;
+ this.stackParser = stackParser;
+ this.modifiers = modifiers;
}
-}
-function encodeAnyValue(value, logger, state, depth) {
- if (state.remainingNodes <= 0)
- return {
- stringValue: TRUNCATED_VALUE
- };
- state.remainingNodes--;
- if (isBoolean(value))
- return {
- boolValue: value
+ buildFromUnknown(input, hint = {}) {
+ const providedMechanism = hint && hint.mechanism;
+ const mechanism = providedMechanism || {
+ handled: true,
+ type: "generic"
};
- if (typeof value == "number") {
- if (!Number.isFinite(value))
- return {
- stringValue: String(value)
- };
- if (Number.isInteger(value)) {
- if (Number.isSafeInteger(value))
- return {
- intValue: String(value)
- };
- if (typeof BigInt == "undefined")
- return {
- stringValue: String(value)
- };
- const decimal = BigInt(value).toString();
- if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
- logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
- return {
- stringValue: decimal
- };
- }
- return {
- intValue: decimal
- };
- }
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
+ const exceptionWithCause = coercingContext.apply(input);
+ const parsingContext = this.buildParsingContext(hint);
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
return {
- doubleValue: value
+ $exception_list: exceptionList,
+ $exception_level: "error"
};
}
- if (typeof value == "string")
- return {
- stringValue: sanitizeString(value)
- };
- if (typeof value == "function")
+ async modifyFrames(exceptionList) {
+ for (const exc of exceptionList)
+ if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
+ exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
+ return exceptionList;
+ }
+ coerceFallback(ctx) {
return {
- stringValue: FUNCTION_VALUE
+ type: "Error",
+ value: "Unknown error",
+ stack: ctx.syntheticException?.stack,
+ synthetic: true
};
- if (typeof value == "symbol")
+ }
+ parseStacktrace(err, ctx) {
+ let cause;
+ if (err.cause != null)
+ cause = this.parseStacktrace(err.cause, ctx);
+ let stack;
+ if (err.stack != "" && err.stack != null)
+ try {
+ stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
+ } catch {}
return {
- stringValue: String(value)
+ ...err,
+ cause,
+ stack,
+ errors: err.errors?.map((child) => this.parseStacktrace(child, ctx))
};
- if (typeof value == "object" && value !== null) {
- if (state.ancestors.has(value))
- return {
- stringValue: CIRCULAR_VALUE
- };
- if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
- return {
- stringValue: TRUNCATED_VALUE
+ }
+ applyChunkIds(frames, chunkIdMap) {
+ return frames.map((frame) => {
+ if (frame.filename && chunkIdMap)
+ frame.chunk_id = chunkIdMap[frame.filename];
+ return frame;
+ });
+ }
+ applyCoercers(input, ctx) {
+ for (const adapter of this.coercers)
+ if (adapter.match(input))
+ return adapter.coerce(input, ctx);
+ return this.coerceFallback(ctx);
+ }
+ async applyModifiers(frames) {
+ let newFrames = frames;
+ for (const modifier of this.modifiers)
+ newFrames = await modifier(newFrames);
+ return newFrames;
+ }
+ convertToExceptionList(exceptionWithStack, mechanism) {
+ const exceptionList = [];
+ const append = (exception, parentId, source) => {
+ const exceptionId = exceptionList.length;
+ const entryMechanism = parentId === undefined ? {
+ type: typeof mechanism.type == "string" && mechanism.type.length > 0 ? mechanism.type : "generic",
+ ...typeof mechanism.handled == "boolean" ? {
+ handled: mechanism.handled
+ } : mechanism.handled === undefined ? {
+ handled: true
+ } : {},
+ synthetic: typeof mechanism.synthetic == "boolean" ? mechanism.synthetic : exception.synthetic,
+ exception_id: exceptionId
+ } : {
+ type: "chained",
+ source,
+ synthetic: exception.synthetic,
+ exception_id: exceptionId,
+ parent_id: parentId
};
- if (value instanceof Date) {
- const time = value.getTime();
- const iso = Number.isFinite(time) ? value.toISOString() : String(value);
- return {
- stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ const currentException = {
+ type: exception.type,
+ value: exception.value,
+ mechanism: entryMechanism
};
- }
- state.ancestors.add(value);
+ if (exception.stack)
+ currentException.stacktrace = {
+ type: "raw",
+ frames: exception.stack
+ };
+ exceptionList.push(currentException);
+ if (exception.cause)
+ append(exception.cause, exceptionId, "cause");
+ for (const child of exception.errors ?? [])
+ append(child, exceptionId, "member");
+ };
+ append(exceptionWithStack);
+ return exceptionList;
+ }
+ buildParsingContext(hint) {
+ const context = {
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
+ skipFirstLines: hint.skipFirstLines ?? 1
+ };
+ return context;
+ }
+ getAggregateErrors(input) {
try {
- try {
- const toJSON = value.toJSON;
- if (typeof toJSON == "function")
- return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
- } catch {}
- if (isArray(value))
- return {
- arrayValue: {
- values: encodeArrayValues(value, logger, state, depth + 1)
+ if (isError(input)) {
+ let prototype = Object.getPrototypeOf(input);
+ for (let depth = 0;prototype && depth < MAX_ERROR_PROTOTYPE_DEPTH; depth++) {
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
+ if (typeof constructor == "function" && constructor.name === "AggregateError") {
+ const errors = input.errors;
+ return isArray(errors) ? errors : undefined;
}
- };
- return {
- kvlistValue: {
- values: encodeKeyValueList(value, logger, state, depth + 1)
+ prototype = Object.getPrototypeOf(prototype);
}
- };
- } finally {
- state.ancestors.delete(value);
- }
+ }
+ } catch {}
}
- return {
- stringValue: sanitizeString(String(value))
- };
-}
-function encodeArrayValues(values, logger, state, depth) {
- const result = [];
- const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
- let index = 0;
- for (;index < itemCount && state.remainingNodes > 0; index++)
- try {
- const element = index in values ? values[index] : undefined;
- if (isNullish(element))
- continue;
- result.push(encodeAnyValue(element, logger, state, depth));
- } catch {
- result.push({
- stringValue: UNSERIALIZABLE_VALUE
- });
- }
- if (values.length > index)
- result.push({
- stringValue: TRUNCATED_VALUE
- });
- return result;
-}
-function encodeKeyValueList(attrs, logger, state, depth) {
- const result = [];
- for (const key in attrs)
- if (propertyIsEnumerable.call(attrs, key)) {
- if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
- logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
- break;
+ buildCoercingContext(mechanism, hint, depth = 0) {
+ let count = 0;
+ let memberInspections = 0;
+ let hasAggregate = false;
+ const seen = new Set;
+ const wrappers = [];
+ const skipped = {};
+ const coerce = (input, depth, wrapperDepth = 0) => {
+ const ctx = createContext(depth, wrapperDepth);
+ const forward = ctx.apply;
+ ctx.apply = (nextInput) => {
+ wrappers.push(input);
+ try {
+ return forward(nextInput);
+ } finally {
+ wrappers.pop();
+ }
+ };
+ if (wrapperDepth > MAX_WRAPPER_RECURSION || wrapperDepth > 0 && wrappers.indexOf(input) !== -1)
+ return this.coerceFallback(ctx);
+ const isReference = typeof input == "object" && input !== null || typeof input == "function";
+ if (wrapperDepth === 0 && count >= MAX_EXCEPTIONS || isReference && seen.has(input))
+ return;
+ if (isReference)
+ seen.add(input);
+ if (wrapperDepth === 0)
+ count++;
+ const errors = this.getAggregateErrors(input);
+ hasAggregate ||= !!errors;
+ let exception;
+ try {
+ exception = this.applyCoercers(input, ctx);
+ if (!exception)
+ throw skipped;
+ } catch (error) {
+ if (error === skipped) {
+ if (wrapperDepth === 0)
+ count--;
+ return;
+ }
+ if (!hasAggregate)
+ throw error;
+ exception = this.coerceFallback(ctx);
}
+ if (!errors || count >= MAX_EXCEPTIONS)
+ return exception;
+ let length;
try {
- const value = attrs[key];
- if (isNull(value) || isUndefined(value))
- continue;
- result.push({
- key: sanitizeString(key),
- value: encodeAnyValue(value, logger, state, depth)
- });
+ length = errors.length;
} catch {
- result.push({
- key: sanitizeString(key),
- value: {
- stringValue: UNSERIALIZABLE_VALUE
- }
- });
+ return exception;
+ }
+ if (!Number.isInteger(length) || length < 0 || length > 4294967295)
+ return exception;
+ const children = [];
+ for (let index = 0;count < MAX_EXCEPTIONS && memberInspections < MAX_AGGREGATE_MEMBER_INSPECTIONS && index < length; index++) {
+ memberInspections++;
+ let child;
+ try {
+ child = ctx.next(errors[index]);
+ } catch {
+ count++;
+ child = this.coerceFallback(createContext(depth + 1));
+ }
+ if (child)
+ children.push(child);
}
- }
- return result;
+ return {
+ ...exception,
+ errors: children
+ };
+ };
+ const createContext = (depth, wrapperDepth = 0) => ({
+ ...hint,
+ syntheticException: depth == 0 ? hint.syntheticException : undefined,
+ mechanism: depth == 0 ? mechanism : {},
+ apply: (input) => {
+ const exception = coerce(input, depth, wrapperDepth + 1);
+ if (!exception)
+ throw skipped;
+ return exception;
+ },
+ next: (input) => coerce(input, depth + 1)
+ });
+ const context = createContext(depth);
+ return {
+ ...context,
+ apply: (input) => coerce(input, depth) ?? this.coerceFallback(context)
+ };
+ }
}
-var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY, INT64_RANGE_LIMIT = 9223372036854776000, propertyIsEnumerable;
-var init_logs_utils = __esm(() => {
- init_utils();
- init_json_utils();
- OTLP_SEVERITY_MAP = {
- trace: {
- text: "TRACE",
- number: 1
- },
- debug: {
- text: "DEBUG",
- number: 5
- },
- info: {
- text: "INFO",
- number: 9
- },
- warn: {
- text: "WARN",
- number: 13
- },
- error: {
- text: "ERROR",
- number: 17
- },
- fatal: {
- text: "FATAL",
- number: 21
- }
- };
- DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
- propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/index.mjs
-var init_logs = __esm(() => {
- init_logs_utils();
- init_types7();
+var MAX_EXCEPTIONS = 50, MAX_AGGREGATE_MEMBER_INSPECTIONS = 1000, MAX_ERROR_PROTOTYPE_DEPTH = 100, MAX_WRAPPER_RECURSION = 4;
+var init_error_properties_builder = __esm(() => {
init_utils();
+ init_chunk_ids();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
-function msToUnixNano(ms) {
- return String(ms) + "000000";
-}
-function seriesKey(type, name, unit, attributes) {
- let attrsKey = "";
- if (attributes) {
- const keys = Object.keys(attributes).sort();
- attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
- }
- return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
-}
-function bucketIndexFor(value, bounds) {
- for (let i = 0;i < bounds.length; i++)
- if (value <= bounds[i])
- return i;
- return bounds.length;
-}
-function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
- return {
- ...config.resourceAttributes,
- "service.name": config.serviceName || "unknown_service",
- ...config.environment && {
- "deployment.environment": config.environment
- },
- ...config.serviceVersion && {
- "service.version": config.serviceVersion
- },
- "telemetry.sdk.name": scopeName,
- "telemetry.sdk.version": scopeVersion
- };
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
+function isAppFilename(filename) {
+ if (!filename || filename === ANONYMOUS_FILENAME)
+ return false;
+ const scheme = URL_SCHEME.exec(filename);
+ return !scheme || APP_URL_SCHEMES.includes(scheme[1].toLowerCase());
}
-function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
- return {
- resourceMetrics: [
- {
- resource: {
- attributes: toOtlpKeyValueList(resourceAttributes)
- },
- scopeMetrics: [
- {
- scope: {
- name: scopeName,
- version: scopeVersion
- },
- metrics
- }
- ]
- }
- ]
+function createFrame(platform, filename, func, lineno, colno) {
+ const frame = {
+ platform,
+ filename,
+ function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
+ in_app: isAppFilename(filename)
};
+ if (!isUndefined(lineno))
+ frame.lineno = lineno;
+ if (!isUndefined(colno))
+ frame.colno = colno;
+ return frame;
}
-var DEFAULT_HISTOGRAM_BOUNDS;
-var init_metrics_utils = __esm(() => {
- init_logs_utils();
- DEFAULT_HISTOGRAM_BOUNDS = [
- 0,
- 5,
- 10,
- 25,
- 50,
- 75,
- 100,
- 250,
- 500,
- 750,
- 1000,
- 2500,
- 5000,
- 7500,
- 1e4
+var UNKNOWN_FUNCTION = "?", ANONYMOUS_FILENAME = "<anonymous>", URL_SCHEME, APP_URL_SCHEMES;
+var init_base = __esm(() => {
+ init_utils();
+ URL_SCHEME = /^([a-z][a-z0-9.+-]+):/i;
+ APP_URL_SCHEMES = [
+ "http",
+ "https",
+ "file",
+ "blob",
+ "app",
+ "capacitor",
+ "ionic",
+ "webpack",
+ "webpack-internal",
+ "ng"
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
-function resolveMetricsConfig(config) {
- const resourceAttributes = config?.resourceAttributes;
- return {
- serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
- serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
- environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
- resourceAttributes,
- beforeSend: config?.beforeSend,
- flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
- maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
- };
-}
-var DEFAULT_FLUSH_INTERVAL_MS = 1e4, DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
-var init_config2 = () => {};
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
+var extractSafariExtensionDetails = (func, filename) => {
+ const isSafariExtension = func.indexOf("safari-extension") !== -1;
+ const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
+ return isSafariExtension || isSafariWebExtension ? [
+ func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
+ ] : [
+ func,
+ filename
+ ];
+};
+var init_safari = __esm(() => {
+ init_base();
+});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
-class PostHogMetrics {
- constructor(_instance, _config, _logger) {
- this._instance = _instance;
- this._config = _config;
- this._logger = _logger;
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- this._generation = 0;
- }
- count(name, value = 1, options) {
- this._capture({
- name,
- type: "count",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
- }
- gauge(name, value, options) {
- this._capture({
- name,
- type: "gauge",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
+var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser = (line, platform) => {
+ const noFnParts = chromeRegexNoFnName.exec(line);
+ if (noFnParts) {
+ const [, filename, line, col] = noFnParts;
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
}
- histogram(name, value, options) {
- this._capture({
- name,
- type: "histogram",
- value,
- unit: options?.unit,
- attributes: options?.attributes
- });
+ const parts = chromeRegex.exec(line);
+ if (parts) {
+ const isEval = parts[2] && parts[2].indexOf("eval") === 0;
+ if (isEval) {
+ const subMatch = chromeEvalRegex.exec(parts[2]);
+ if (subMatch) {
+ parts[2] = subMatch[1];
+ parts[3] = subMatch[2];
+ parts[4] = subMatch[3];
+ }
+ }
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
}
- flush() {
- const prev = this._flushPromise;
- const run = async () => {
- if (prev)
- await prev.catch(() => {});
- await this._doFlush();
- };
- const p = run().finally(() => {
- if (this._flushPromise === p)
- this._flushPromise = null;
- });
- this._flushPromise = p;
- return p;
- }
- drainWindow() {
- if (this._series.size === 0)
- return null;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- return this._buildPayload(window);
- }
- reset() {
- this._generation++;
- this._clearFlushTimer();
- this._series = new Map;
- this._flushPromise = null;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- }
- _capture(sample) {
- if (this._instance.isDisabled || this._instance.optedOut)
- return;
- const filtered = this._runBeforeSend(sample);
- if (filtered === null)
- return;
- if (!filtered.name || typeof filtered.name != "string")
- return void this._logger.warn("Dropping metric with empty name");
- if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
- return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
- if (filtered.type === "count" && filtered.value < 0)
- return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
- let attributes;
- let key;
- try {
- attributes = filtered.attributes ? {
- ...filtered.attributes
- } : undefined;
- key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
- } catch (e) {
- this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
- return;
- }
- let state = this._series.get(key);
- if (!state) {
- if (!this._admitNewSeries())
- return;
- state = {
- name: filtered.name,
- type: filtered.type,
- unit: filtered.unit,
- attributes,
- windowStartMs: Date.now()
- };
- this._series.set(key, state);
- }
- const seenType = this._typeByName.get(filtered.name);
- if (seenType === undefined)
- this._typeByName.set(filtered.name, filtered.type);
- else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
- this._typeCollisionWarned.add(filtered.name);
- this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
- }
- this._fold(state, filtered.value);
- this._armFlushTimer();
- }
- _admitNewSeries() {
- if (this._series.size < this._config.maxSeriesPerFlush)
- return true;
- if (!this._seriesCapWarned) {
- this._seriesCapWarned = true;
- this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
- }
- return false;
- }
- _fold(state, value) {
- switch (state.type) {
- case "count":
- state.total = (state.total ?? 0) + value;
- break;
- case "gauge":
- state.last = value;
- break;
- case "histogram": {
- if (!state.hist)
- state.hist = {
- count: 0,
- sum: 0,
- min: value,
- max: value,
- bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
- };
- const hist = state.hist;
- hist.count += 1;
- hist.sum += value;
- hist.min = Math.min(hist.min, value);
- hist.max = Math.max(hist.max, value);
- hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
- break;
- }
- }
- }
- _runBeforeSend(sample) {
- const beforeSend = this._config.beforeSend;
- if (!beforeSend)
- return sample;
- const fns = isArray(beforeSend) ? beforeSend : [
- beforeSend
- ];
- let result = sample;
- for (const fn of fns)
- try {
- const next = fn(result);
- if (!next) {
- this._logger.info("Metric was rejected in beforeSend function");
- return null;
- }
- result = next;
- } catch (e) {
- this._logger.error("Error in beforeSend function for metric:", e);
- return null;
- }
- return result;
- }
- _armFlushTimer() {
- if (this._flushTimer)
- return;
- this._flushTimer = safeSetTimeout(() => {
- this._flushTimer = undefined;
- this.flush().catch((e) => {
- this._logger.error("Metrics flush failed:", e);
- });
- }, this._config.flushIntervalMs);
- }
- _clearFlushTimer() {
- if (this._flushTimer) {
- clearTimeout(this._flushTimer);
- this._flushTimer = undefined;
- }
- }
- async _doFlush() {
- if (this._series.size === 0)
- return;
- const window = this._series;
- this._series = new Map;
- this._seriesCapWarned = false;
- this._typeByName = new Map;
- this._typeCollisionWarned = new Set;
- const generation = this._generation;
- const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
- if (generation !== this._generation)
- return;
- switch (outcome.kind) {
- case "ok":
- return;
- case "retry-later":
- this._mergeWindowBack(window);
- this._armFlushTimer();
- return;
- case "too-large":
- this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
- return;
- case "fatal":
- this._logger.error("Failed to send metrics batch:", outcome.error);
- return;
- }
- }
- _buildPayload(window) {
- return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
- }
- _buildMetrics(window) {
- const nowNano = msToUnixNano(Date.now());
- const byMetric = new Map;
- for (const state of window.values()) {
- const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
- let metric = byMetric.get(metricKey);
- if (!metric) {
- metric = {
- name: state.name,
- ...state.unit && {
- unit: state.unit
- }
- };
- if (state.type === "count")
- metric.sum = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- isMonotonic: true,
- dataPoints: []
- };
- else if (state.type === "gauge")
- metric.gauge = {
- dataPoints: []
- };
- else
- metric.histogram = {
- aggregationTemporality: OTLP_TEMPORALITY_DELTA,
- dataPoints: []
- };
- byMetric.set(metricKey, metric);
- }
- const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
- const startNano = msToUnixNano(state.windowStartMs);
- if (state.type === "count") {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- asDouble: state.total ?? 0
- };
- metric.sum.dataPoints.push(dp);
- } else if (state.type === "gauge") {
- const dp = {
- attributes,
- timeUnixNano: nowNano,
- asDouble: state.last ?? 0
- };
- metric.gauge.dataPoints.push(dp);
- } else if (state.hist) {
- const dp = {
- attributes,
- startTimeUnixNano: startNano,
- timeUnixNano: nowNano,
- count: state.hist.count,
- sum: state.hist.sum,
- min: state.hist.min,
- max: state.hist.max,
- bucketCounts: state.hist.bucketCounts,
- explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
- };
- metric.histogram.dataPoints.push(dp);
- }
- }
- return Array.from(byMetric.values());
- }
- _mergeWindowBack(window) {
- for (const [key, old] of window) {
- const current = this._series.get(key);
- if (!current) {
- if (this._admitNewSeries())
- this._series.set(key, old);
- continue;
- }
- current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
- switch (current.type) {
- case "count":
- current.total = (current.total ?? 0) + (old.total ?? 0);
- break;
- case "gauge":
- break;
- case "histogram":
- if (old.hist)
- if (current.hist) {
- current.hist.count += old.hist.count;
- current.hist.sum += old.hist.sum;
- current.hist.min = Math.min(current.hist.min, old.hist.min);
- current.hist.max = Math.max(current.hist.max, old.hist.max);
- for (let i = 0;i < current.hist.bucketCounts.length; i++)
- current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
- } else
- current.hist = old.hist;
- break;
- }
- }
- }
-}
-var OTLP_TEMPORALITY_DELTA = 1;
-var init_metrics = __esm(() => {
- init_utils();
- init_logs_utils();
- init_metrics_utils();
- init_config2();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/surveys/validation.mjs
-var init_validation = __esm(() => {
- init_types7();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/cookie.mjs
-var init_cookie = __esm(() => {
- init_utils();
- init_uuidv7();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
-class SimpleEventEmitter {
- constructor() {
- this.events = {};
- this.events = {};
- }
- on(event, listener) {
- if (!this.events[event])
- this.events[event] = [];
- this.events[event].push(listener);
- return () => {
- this.events[event] = this.events[event].filter((x) => x !== listener);
- };
- }
- emit(event, payload) {
- for (const listener of this.events[event] || [])
- listener(payload);
- for (const listener of this.events["*"] || [])
- listener(event, payload);
- }
-}
-var init_eventemitter = () => {};
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
-function getFilenameToChunkIdMap(stackParser) {
- const chunkIdMap = globalThis._posthogChunkIds;
- if (!chunkIdMap)
- return;
- const chunkIdKeys = Object.keys(chunkIdMap);
- if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
- return cachedFilenameChunkIds;
- lastKeysCount = chunkIdKeys.length;
- cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
- if (!parsedStackResults)
- parsedStackResults = {};
- const result = parsedStackResults[stackKey];
- if (result)
- acc[result[0]] = result[1];
- else {
- const parsedStack = stackParser(stackKey);
- for (let i = parsedStack.length - 1;i >= 0; i--) {
- const stackFrame = parsedStack[i];
- const filename = stackFrame?.filename;
- const chunkId = chunkIdMap[stackKey];
- if (filename && chunkId) {
- acc[filename] = chunkId;
- parsedStackResults[stackKey] = [
- filename,
- chunkId
- ];
- break;
- }
- }
- }
- return acc;
- }, {});
- return cachedFilenameChunkIds;
-}
-var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
-var init_chunk_ids = () => {};
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
-class ErrorPropertiesBuilder {
- constructor(coercers, stackParser, modifiers = []) {
- this.coercers = coercers;
- this.stackParser = stackParser;
- this.modifiers = modifiers;
- }
- buildFromUnknown(input, hint = {}) {
- const providedMechanism = hint && hint.mechanism;
- const mechanism = providedMechanism || {
- handled: true,
- type: "generic"
- };
- const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
- const exceptionWithCause = coercingContext.apply(input);
- const parsingContext = this.buildParsingContext(hint);
- const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
- const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
- return {
- $exception_list: exceptionList,
- $exception_level: "error"
- };
- }
- async modifyFrames(exceptionList) {
- for (const exc of exceptionList)
- if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
- exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
- return exceptionList;
- }
- coerceFallback(ctx) {
- return {
- type: "Error",
- value: "Unknown error",
- stack: ctx.syntheticException?.stack,
- synthetic: true
- };
- }
- parseStacktrace(err, ctx) {
- let cause;
- if (err.cause != null)
- cause = this.parseStacktrace(err.cause, ctx);
- let stack;
- if (err.stack != "" && err.stack != null)
- stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
- return {
- ...err,
- cause,
- stack
- };
- }
- applyChunkIds(frames, chunkIdMap) {
- return frames.map((frame) => {
- if (frame.filename && chunkIdMap)
- frame.chunk_id = chunkIdMap[frame.filename];
- return frame;
- });
- }
- applyCoercers(input, ctx) {
- for (const adapter of this.coercers)
- if (adapter.match(input))
- return adapter.coerce(input, ctx);
- return this.coerceFallback(ctx);
- }
- async applyModifiers(frames) {
- let newFrames = frames;
- for (const modifier of this.modifiers)
- newFrames = await modifier(newFrames);
- return newFrames;
- }
- convertToExceptionList(exceptionWithStack, mechanism) {
- const currentException = {
- type: exceptionWithStack.type,
- value: exceptionWithStack.value,
- mechanism: {
- type: mechanism.type ?? "generic",
- handled: mechanism.handled ?? true,
- synthetic: exceptionWithStack.synthetic ?? false
- }
- };
- if (exceptionWithStack.stack)
- currentException.stacktrace = {
- type: "raw",
- frames: exceptionWithStack.stack
- };
- const exceptionList = [
- currentException
- ];
- if (exceptionWithStack.cause != null)
- exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
- ...mechanism,
- handled: true
- }));
- return exceptionList;
- }
- buildParsingContext(hint) {
- const context = {
- chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
- skipFirstLines: hint.skipFirstLines ?? 1
- };
- return context;
- }
- buildCoercingContext(mechanism, hint, depth = 0) {
- const coerce = (input, depth) => {
- if (!(depth <= MAX_CAUSE_RECURSION))
- return;
- {
- const ctx = this.buildCoercingContext(mechanism, hint, depth);
- return this.applyCoercers(input, ctx);
- }
- };
- const context = {
- ...hint,
- syntheticException: depth == 0 ? hint.syntheticException : undefined,
- mechanism,
- apply: (input) => coerce(input, depth),
- next: (input) => coerce(input, depth + 1)
- };
- return context;
- }
-}
-var MAX_CAUSE_RECURSION = 4;
-var init_error_properties_builder = __esm(() => {
- init_utils();
- init_chunk_ids();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
-function createFrame(platform, filename, func, lineno, colno) {
- const frame = {
- platform,
- filename,
- function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
- in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
- };
- if (!isUndefined(lineno))
- frame.lineno = lineno;
- if (!isUndefined(colno))
- frame.colno = colno;
- return frame;
-}
-var UNKNOWN_FUNCTION = "?", MASKED_URL_PREFIX = "webkit-masked-url://", ANONYMOUS_FILENAME = "<anonymous>";
-var init_base = __esm(() => {
- init_utils();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
-var extractSafariExtensionDetails = (func, filename) => {
- const isSafariExtension = func.indexOf("safari-extension") !== -1;
- const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
- return isSafariExtension || isSafariWebExtension ? [
- func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
- isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
- ] : [
- func,
- filename
- ];
-};
-var init_safari = __esm(() => {
- init_base();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
-var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser = (line, platform) => {
- const noFnParts = chromeRegexNoFnName.exec(line);
- if (noFnParts) {
- const [, filename, line, col] = noFnParts;
- return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
- }
- const parts = chromeRegex.exec(line);
- if (parts) {
- const isEval = parts[2] && parts[2].indexOf("eval") === 0;
- if (isEval) {
- const subMatch = chromeEvalRegex.exec(parts[2]);
- if (subMatch) {
- parts[2] = subMatch[1];
- parts[3] = subMatch[2];
- parts[4] = subMatch[3];
- }
- }
- const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
- return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
- }
-};
-var init_chrome = __esm(() => {
- init_base();
- init_safari();
- chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
- chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
- chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
-var geckoREgex, geckoEvalRegex, geckoStackLineParser = (line, platform) => {
- const parts = geckoREgex.exec(line);
- if (parts) {
- const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
- if (isEval) {
- const subMatch = geckoEvalRegex.exec(parts[3]);
- if (subMatch) {
- parts[1] = parts[1] || "eval";
- parts[3] = subMatch[1];
- parts[4] = subMatch[2];
- parts[5] = "";
- }
- }
- let filename = parts[3];
- let func = parts[1] || UNKNOWN_FUNCTION;
- [func, filename] = extractSafariExtensionDetails(func, filename);
- return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
+};
+var init_chrome = __esm(() => {
+ init_base();
+ init_safari();
+ chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
+ chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
+ chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
+var geckoREgex, geckoEvalRegex, geckoStackLineParser = (line, platform) => {
+ const parts = geckoREgex.exec(line);
+ if (parts) {
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
+ if (isEval) {
+ const subMatch = geckoEvalRegex.exec(parts[3]);
+ if (subMatch) {
+ parts[1] = parts[1] || "eval";
+ parts[3] = subMatch[1];
+ parts[4] = subMatch[2];
+ parts[5] = "";
+ }
+ }
+ let filename = parts[3];
+ let func = parts[1] || UNKNOWN_FUNCTION;
+ [func, filename] = extractSafariExtensionDetails(func, filename);
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
}
};
var init_gecko = __esm(() => {
@@ -79416,17 +80051,17 @@ var init_gecko = __esm(() => {
geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
var init_winjs = __esm(() => {
init_base();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
var init_opera = __esm(() => {
init_base();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
function filenameIsInApp(filename, isNative = false) {
const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
return !isInternal && filename !== undefined && !filename.includes("node_modules/");
@@ -79502,13 +80137,83 @@ var init_node = __esm(() => {
PROMISE_INDEX = /^index \d+$/;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
-function reverseAndStripFrames(stack) {
- if (!stack.length)
- return [];
- const localStack = Array.from(stack);
- localStack.reverse();
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
+function isSameFrame(a, b) {
+ return a.filename === b.filename && a.function === b.function && a.module === b.module && a.lineno === b.lineno && a.colno === b.colno;
+}
+function collapseRepeatedCycle(frames) {
+ for (let length = 1;length <= MAX_REPEATED_CYCLE_LENGTH; length++) {
+ const start = frames.length - 2 * length;
+ if (start < 0)
+ break;
+ let isCycle = true;
+ for (let offset = 0;offset < length; offset++) {
+ const inner = frames[start + offset];
+ if (!isSameFrame(inner, frames[start + length + offset])) {
+ isCycle = false;
+ break;
+ }
+ }
+ if (isCycle) {
+ for (let offset = 0;offset < length; offset++)
+ frames[start + offset] = frames[start + length + offset];
+ frames.length = start + length;
+ return {
+ start,
+ length
+ };
+ }
+ }
+}
+function trimPartialCycle(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ const partialLength = partialCycleLength(frames, cycle);
+ if (partialLength)
+ frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength);
+}
+function innermostPartialCycleLength(frames, cycle) {
+ let partialStart = cycle.start;
+ while (partialStart > 0 && isSameFrame(frames[partialStart - 1], frames[partialStart - 1 + cycle.length]))
+ partialStart--;
+ return cycle.start - partialStart;
+}
+function partialCycleLength(frames, cycle) {
+ const copyEnd = cycle.start + cycle.length;
+ let partialEnd = copyEnd;
+ while (partialEnd < frames.length && isSameFrame(frames[partialEnd], frames[partialEnd - cycle.length]))
+ partialEnd++;
+ return partialEnd - copyEnd;
+}
+function survivingFrameCount(frames, cycles) {
+ const innermostCycle = cycles[0];
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0);
+ for (const cycle of cycles)
+ count -= partialCycleLength(frames, cycle);
+ return count;
+}
+function canonicalizeCycleRotation(frames) {
+ const keys = frames.map((frame) => `${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`);
+ let first = 0;
+ for (let i = 1;i < keys.length; i++)
+ if (isSmallerRotation(keys, i, first))
+ first = i;
+ frames.push(...frames.splice(0, first));
+}
+function isSmallerRotation(keys, candidate, best) {
+ for (let offset = 0;offset < keys.length; offset++) {
+ const left = keys[(candidate + offset) % keys.length];
+ const right = keys[(best + offset) % keys.length];
+ if (left !== right)
+ return left < right;
+ }
+ return false;
+}
+function reverseAndStripFrames(stack) {
+ if (!stack.length)
+ return [];
+ const localStack = Array.from(stack);
+ localStack.reverse();
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
...frame,
filename: frame.filename || getLastStackFrame(localStack).filename,
function: frame.function || UNKNOWN_FUNCTION
@@ -79525,7 +80230,9 @@ function createStackParser(platform, ...parsers) {
const frames = [];
const lines = stack.split(`
`);
- for (let i = skipFirstLines;i < lines.length; i++) {
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT);
+ const repeatedCycles = [];
+ for (let i = skipFirstLines;i < endLine; i++) {
const line = lines[i];
if (line.length > 1024)
continue;
@@ -79535,17 +80242,41 @@ function createStackParser(platform, ...parsers) {
const frame = parser(cleanedLine, platform);
if (frame) {
frames.push(frame);
+ const cycle = collapseRepeatedCycle(frames);
+ if (cycle) {
+ for (let i = repeatedCycles.length - 1;i >= 0; i--) {
+ const previous = repeatedCycles[i];
+ if (previous.start + previous.length <= cycle.start)
+ break;
+ repeatedCycles.pop();
+ }
+ repeatedCycles.push(cycle);
+ }
break;
}
}
- if (frames.length >= STACKTRACE_FRAME_LIMIT)
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT)
break;
}
}
+ const sections = [
+ ...repeatedCycles
+ ].sort((a, b) => b.start - a.start);
+ const innermostSection = sections[sections.length - 1];
+ if (innermostSection) {
+ const trimmed = innermostPartialCycleLength(frames, innermostSection);
+ frames.splice(innermostSection.start - trimmed, trimmed);
+ for (const cycle of sections)
+ cycle.start -= trimmed;
+ }
+ for (const cycle of sections)
+ trimPartialCycle(frames, cycle);
+ if (repeatedCycles.some((cycle) => cycle.start === 0 && frames.length === cycle.length))
+ canonicalizeCycleRotation(frames);
return reverseAndStripFrames(frames);
};
}
-var WEBPACK_ERROR_REGEXP, STACKTRACE_FRAME_LIMIT = 50;
+var WEBPACK_ERROR_REGEXP, STACKTRACE_FRAME_LIMIT = 50, MAX_REPEATED_CYCLE_LENGTH = 10, STACKTRACE_LINE_LIMIT = 1000;
var init_parsers = __esm(() => {
init_base();
init_chrome();
@@ -79556,23 +80287,24 @@ var init_parsers = __esm(() => {
WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
var init_dom_exception_coercer = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
class ErrorCoercer {
match(err) {
return isError(err);
}
coerce(err, ctx) {
const stack = this.getStack(err);
- const synthetic = stack === undefined;
+ const replacementStack = stack === undefined ? ctx.syntheticException?.stack : undefined;
+ const synthetic = !!replacementStack;
return {
type: this.getType(err),
value: this.getMessage(err, ctx),
- stack: stack ?? ctx.syntheticException?.stack,
+ stack: stack ?? replacementStack,
cause: err.cause ? ctx.next(err.cause) : undefined,
synthetic
};
@@ -79587,19 +80319,27 @@ class ErrorCoercer {
return String(message);
}
getStack(err) {
- return err.stacktrace || err.stack || undefined;
+ try {
+ const stacktrace = err.stacktrace;
+ if (typeof stacktrace == "string" && stacktrace.length > 0)
+ return stacktrace;
+ const stack = err.stack;
+ return typeof stack == "string" && stack.length > 0 ? stack : undefined;
+ } catch {
+ return;
+ }
}
}
var init_error_coercer = __esm(() => {
init_type_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
var init_error_event_coercer = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
class StringCoercer {
match(input) {
return typeof input == "string";
@@ -79632,7 +80372,7 @@ var init_string_coercer = __esm(() => {
ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/types.mjs
var severityLevels;
var init_types8 = __esm(() => {
severityLevels = [
@@ -79645,7 +80385,7 @@ var init_types8 = __esm(() => {
];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
function extractExceptionKeysForMessage(err, maxLength = 40) {
const keys = Object.keys(err);
keys.sort();
@@ -79663,7 +80403,7 @@ function extractExceptionKeysForMessage(err, maxLength = 40) {
}
var init_utils2 = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
class ObjectCoercer {
match(candidate) {
return typeof candidate == "object" && candidate !== null;
@@ -79734,7 +80474,7 @@ var init_object_coercer = __esm(() => {
init_utils2();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
class EventCoercer {
match(err) {
return isEvent(err);
@@ -79754,7 +80494,7 @@ var init_event_coercer = __esm(() => {
init_utils2();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
class PrimitiveCoercer {
match(candidate) {
return isPrimitive(candidate);
@@ -79772,12 +80512,12 @@ var init_primitive_coercer = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
var init_promise_rejection_event = __esm(() => {
init_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
var init_coercers = __esm(() => {
init_dom_exception_coercer();
init_error_coercer();
@@ -79789,7 +80529,7 @@ var init_coercers = __esm(() => {
init_promise_rejection_event();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/utils.mjs
class ReduceableCache {
constructor(_maxSize) {
this._maxSize = _maxSize;
@@ -79816,7 +80556,7 @@ class ReduceableCache {
}
var init_utils3 = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
var EXCEPTION_STEP_INTERNAL_FIELDS, RESERVED_EXCEPTION_STEP_KEYS;
var init_exception_steps = __esm(() => {
init_utils();
@@ -79830,14 +80570,14 @@ var init_exception_steps = __esm(() => {
]);
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/release.mjs
function getInjectedReleaseId() {
const injected = globalThis._posthogReleaseId;
return typeof injected == "string" && injected.length > 0 ? injected : undefined;
}
var init_release = () => {};
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/error-tracking/index.mjs
var init_error_tracking = __esm(() => {
init_error_properties_builder();
init_parsers();
@@ -79847,7 +80587,232 @@ var init_error_tracking = __esm(() => {
init_release();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/cookie.mjs
+var init_cookie = __esm(() => {
+ init_utils();
+ init_uuidv7();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagUtils.mjs
+function getFlagDetailFromFlagAndPayload(key, value, payload) {
+ return {
+ key,
+ enabled: typeof value == "string" ? true : value,
+ variant: typeof value == "string" ? value : undefined,
+ reason: undefined,
+ metadata: {
+ id: undefined,
+ version: undefined,
+ payload: payload ? JSON.stringify(payload) : undefined,
+ description: undefined
+ }
+ };
+}
+var normalizeFlagsResponse = (flagsResponse) => {
+ if ("flags" in flagsResponse) {
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads
+ };
+ }
+ {
+ const featureFlags = flagsResponse.featureFlags ?? {};
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
+ k,
+ parsePayload(v)
+ ]));
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
+ key,
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
+ ]));
+ return {
+ ...flagsResponse,
+ featureFlags,
+ featureFlagPayloads,
+ flags
+ };
+ }
+}, getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
+ key,
+ getFeatureFlagValue(detail)
+]).filter(([, value]) => value !== undefined)), getPayloadsFromFlags = (flags) => {
+ const safeFlags = flags ?? {};
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
+ const details = safeFlags[flag];
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
+ }).map((flag) => {
+ const payload = safeFlags[flag].metadata?.payload;
+ return [
+ flag,
+ payload ? parsePayload(payload) : undefined
+ ];
+ }));
+}, getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled, parsePayload = (response) => {
+ if (typeof response != "string")
+ return response;
+ try {
+ return JSON.parse(response);
+ } catch {
+ return response;
+ }
+}, MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
+ const minimal = {};
+ const copyKey = (key) => {
+ if (properties[key] !== undefined)
+ minimal[key] = properties[key];
+ };
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
+ transportKeys.forEach(copyKey);
+ return minimal;
+};
+var init_featureFlagUtils = __esm(() => {
+ MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_content",
+ "utm_term",
+ "gad_source",
+ "mc_cid",
+ "gclid",
+ "gclsrc",
+ "dclid",
+ "gbraid",
+ "wbraid",
+ "fbclid",
+ "msclkid",
+ "twclid",
+ "li_fat_id",
+ "igshid",
+ "ttclid",
+ "rdt_cid",
+ "epik",
+ "qclid",
+ "sccid",
+ "irclid",
+ "_kx"
+ ];
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
+ "$feature_flag",
+ "$feature_flag_response",
+ "$feature_flag_has_experiment",
+ "$feature_flag_id",
+ "$feature_flag_version",
+ "$feature_flag_reason",
+ "$feature_flag_request_id",
+ "$feature_flag_evaluated_at",
+ "$feature_flag_error",
+ "locally_evaluated",
+ "$groups",
+ "$process_person_profile",
+ "$geoip_disable",
+ "$current_url",
+ "$pathname",
+ "$referring_domain",
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
+ "$session_id",
+ "$window_id",
+ "$lib",
+ "$lib_version",
+ "$device_id",
+ "$is_server"
+ ];
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/eventemitter.mjs
+class SimpleEventEmitter {
+ constructor() {
+ this.events = {};
+ this.events = {};
+ }
+ on(event, listener) {
+ if (!this.events[event])
+ this.events[event] = [];
+ this.events[event].push(listener);
+ return () => {
+ this.events[event] = this.events[event].filter((x) => x !== listener);
+ };
+ }
+ emit(event, payload) {
+ for (const listener of this.events[event] || [])
+ listener(payload);
+ for (const listener of this.events["*"] || [])
+ listener(event, payload);
+ }
+}
+var init_eventemitter = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/gzip.mjs
+function isGzipSupported() {
+ return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
+}
+async function gzipCompress(input, isDebug = true, options) {
+ try {
+ const inputBytes = new TextEncoder().encode(input);
+ const compressedStream = new globalThis.CompressionStream("gzip");
+ const writer = compressedStream.writable.getWriter();
+ const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
+ try {
+ await writer.abort(err);
+ } catch {}
+ throw err;
+ });
+ const responsePromise = new Response(compressedStream.readable).blob();
+ const [compressed] = await Promise.all([
+ responsePromise,
+ writePromise
+ ]);
+ await validateNativeGzip(compressed, inputBytes);
+ return compressed;
+ } catch (error) {
+ if (options?.rethrow)
+ throw error;
+ if (isDebug)
+ console.error("Failed to gzip compress data", error);
+ return null;
+ }
+}
+var NATIVE_GZIP_VALIDATION_ERROR = "NativeGzipValidationError", GZIP_MAGIC_FIRST_BYTE = 31, GZIP_MAGIC_SECOND_BYTE = 139, GZIP_DEFLATE_METHOD = 8, hasGzipMagic = (bytes) => bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE, crc32Table, getCrc32Table = () => {
+ if (crc32Table)
+ return crc32Table;
+ crc32Table = [];
+ for (let i = 0;i < 256; i++) {
+ let crc = i;
+ for (let j = 0;j < 8; j++)
+ crc = 1 & crc ? 3988292384 ^ crc >>> 1 : crc >>> 1;
+ crc32Table[i] = crc >>> 0;
+ }
+ return crc32Table;
+}, crc32 = (bytes) => {
+ const table = getCrc32Table();
+ let crc = 4294967295;
+ for (let i = 0;i < bytes.length; i++)
+ crc = table[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
+ return (4294967295 ^ crc) >>> 0;
+}, throwNativeGzipValidationError = (reason) => {
+ throw createNamedError(NATIVE_GZIP_VALIDATION_ERROR, `Native gzip produced invalid output: ${reason}`);
+}, validateNativeGzip = async (compressed, inputBytes) => {
+ if (compressed.size < 18)
+ throwNativeGzipValidationError("too-short");
+ const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());
+ if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD)
+ throwNativeGzipValidationError("invalid-header");
+ const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());
+ if (trailer.getUint32(0, true) !== crc32(inputBytes))
+ throwNativeGzipValidationError("invalid-crc");
+ const inputSize = inputBytes.length >>> 0;
+ if (trailer.getUint32(4, true) !== inputSize)
+ throwNativeGzipValidationError("invalid-size");
+};
+var init_gzip = __esm(() => {
+ init_types7();
+ init_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
async function logFlushError(err) {
if (err instanceof PostHogFetchHttpError) {
let text = "";
@@ -79877,6 +80842,17 @@ function isRetryableFlagsFetchError(err) {
const code = cause?.code ?? cause?.cause?.code;
return code !== "ECONNREFUSED";
}
+function byteLengthOf(body) {
+ try {
+ if (typeof body != "string")
+ return body instanceof Uint8Array ? body.byteLength : body.size;
+ if ("u" > typeof Buffer)
+ return Buffer.byteLength(body, STRING_FORMAT);
+ return new TextEncoder().encode(body).length;
+ } catch {
+ return 0;
+ }
+}
function isPostHogFetchContentTooLargeError(err) {
return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
}
@@ -79903,6 +80879,7 @@ class PostHogCoreStateless {
new PrimitiveCoercer
], createDefaultStackParser());
}
+ getEvaluationRuntime() {}
constructor(apiKey, options = {}) {
this.flushPromise = null;
this.pendingFlushPromise = null;
@@ -80151,6 +81128,9 @@ class PostHogCoreStateless {
requestData.$device_id = personProperties.$device_id;
if (this.evaluationContexts && this.evaluationContexts.length > 0)
requestData.evaluation_contexts = this.evaluationContexts;
+ const evaluationRuntime = this.getEvaluationRuntime();
+ if (evaluationRuntime)
+ requestData.evaluation_runtime = evaluationRuntime;
const fetchOptions = {
method: "POST",
headers: {
@@ -80466,10 +81446,13 @@ class PostHogCoreStateless {
flushBackground() {
if (this.pendingFlushPromise)
return;
- this.flush().catch(async (err) => {
+ this.flushAutomatic().catch(async (err) => {
await logFlushError(err);
});
}
+ flushAutomatic() {
+ return this.flush();
+ }
async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
let iteration = 0;
@@ -80646,352 +81629,3054 @@ class PostHogCoreStateless {
sentFromRoute += batchMessages.length;
}
}
- async _sendLogsBatch(payload) {
- if (this.disabled)
+ async _sendOtlpBatch({ path, auth, payload }) {
+ if (this.disabled)
+ return {
+ kind: "fatal",
+ error: new Error("The client is disabled")
+ };
+ let serialized;
+ try {
+ serialized = JSON.stringify(payload);
+ } catch (error) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Could not serialize a ${path} batch; reporting it as too large`, error));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const payloadBytes = byteLengthOf(serialized);
+ if (payloadBytes > OTLP_MAX_BODY_BYTES) {
+ this.logMsgIfDebug(() => console.warn(`[PostHog] Not sending a ${path} batch of ${payloadBytes} bytes: the endpoint accepts at most ${OTLP_MAX_BODY_BYTES}`));
+ return {
+ kind: "too-large",
+ measuredLocally: true
+ };
+ }
+ const url = auth === "bearer" ? `${this.host}/i/v1/${path}` : `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
+ const body = gzippedPayload || serialized;
+ const fetchOptions = {
+ method: "POST",
+ headers: {
+ ...this.getCustomHeaders(),
+ "Content-Type": "application/json",
+ ...auth === "bearer" && {
+ Authorization: `Bearer ${this.apiKey}`
+ },
+ ...gzippedPayload !== null && {
+ "Content-Encoding": "gzip"
+ }
+ },
+ body
+ };
+ try {
+ await this.fetchWithRetry(url, fetchOptions, {
+ type: "successful-write"
+ }, {
+ retryCheck: (err) => {
+ if (isPostHogFetchContentTooLargeError(err))
+ return false;
+ if (err instanceof PostHogFetchHttpError && err.retryAfterMs !== undefined)
+ return false;
+ return isPostHogFetchRetryableError(err);
+ }
+ });
+ return {
+ kind: "ok"
+ };
+ } catch (err) {
+ if (isPostHogFetchContentTooLargeError(err))
+ return {
+ kind: "too-large"
+ };
+ if (isPostHogFetchRetryableError(err)) {
+ const retryAfterMs = err instanceof PostHogFetchHttpError ? err.retryAfterMs : undefined;
+ return {
+ kind: "retry-later",
+ error: err,
+ ...retryAfterMs !== undefined && {
+ retryAfterMs
+ }
+ };
+ }
+ return {
+ kind: "fatal",
+ error: err
+ };
+ }
+ }
+ async _sendLogsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "logs",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendMetricsBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "metrics",
+ auth: "query-token",
+ payload
+ });
+ }
+ async _sendTracesBatch(payload) {
+ return this._sendOtlpBatch({
+ path: "traces",
+ auth: "bearer",
+ payload
+ });
+ }
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
+ const body = options.body ? options.body : "";
+ const reqByteLength = byteLengthOf(body);
+ const retriableOptions = {
+ ...this._retryOptions,
+ ...retryOptions
+ };
+ let attempt = 0;
+ return await retriable(async () => {
+ attempt++;
+ const ctrl = new AbortController;
+ const timeoutMs = requestTimeout ?? this.requestTimeout;
+ const requestDeadline = Date.now() + timeoutMs;
+ let timer;
+ const deadline = new Promise((_resolve, reject) => {
+ timer = safeSetTimeout(() => {
+ const timeoutError = createNamedError("AbortError", `Request timed out after ${timeoutMs}ms`);
+ reject(timeoutError);
+ ctrl.abort(timeoutError);
+ }, timeoutMs);
+ });
+ let res;
+ let responseAccepted = false;
+ let cancellation;
+ const cancelBody = () => cancellation ??= (async () => {
+ try {
+ await res?.body?.cancel();
+ } catch {}
+ })();
+ try {
+ let fetchPromise;
+ try {
+ fetchPromise = this.fetch(url, {
+ signal: ctrl.signal,
+ ...options
+ });
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ fetchPromise.then((lateResponse) => {
+ if (ctrl.signal.aborted && !responseAccepted)
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
+ }).catch(() => {});
+ try {
+ res = await Promise.race([
+ fetchPromise,
+ deadline
+ ]);
+ responseAccepted = true;
+ } catch (e) {
+ throw new PostHogFetchNetworkError(e);
+ }
+ const isNoCors = options.mode === "no-cors";
+ const maxSuccessStatus = responseHandling.type === "successful-write" ? 300 : 400;
+ if (!isNoCors && (res.status < 200 || res.status >= maxSuccessStatus))
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
+ if (responseHandling.type === "successful-write") {
+ try {
+ await Promise.race([
+ cancelBody(),
+ deadline
+ ]);
+ } catch {}
+ return;
+ }
+ try {
+ return await Promise.race([
+ responseHandling.consume(res),
+ deadline
+ ]);
+ } catch (e) {
+ if (ctrl.signal.aborted)
+ throw new PostHogFetchNetworkError(e);
+ throw e;
+ }
+ } finally {
+ clearTimeout(timer);
+ if (ctrl.signal.aborted && res)
+ cancelBody();
+ }
+ }, {
+ ...retriableOptions,
+ retryCheck: (error) => {
+ const shouldRetry = retriableOptions.retryCheck(error);
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
+ error.cancelResponseBody();
+ return shouldRetry;
+ }
+ });
+ }
+ async _shutdown(shutdownTimeoutMs = 30000) {
+ await this._initPromise;
+ let hasTimedOut = false;
+ this.clearFlushTimer();
+ if (this.disabled)
+ return;
+ const doShutdown = async () => {
+ try {
+ await this.promiseQueue.join();
+ while (true) {
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
+ if (!hasQueuedEvents)
+ break;
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
+ await this.flush();
+ if (hasTimedOut)
+ break;
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
+ break;
+ }
+ }
+ } catch (e) {
+ if (!isPostHogFetchError(e))
+ throw e;
+ await logFlushError(e);
+ }
+ };
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
+ shutdownTimeoutMs
+ });
+ hasTimedOut = true;
+ });
+ }
+ async shutdown(shutdownTimeoutMs = 30000) {
+ if (this.shutdownPromise)
+ this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
+ else
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
+ this.shutdownPromise = null;
+ });
+ return this.shutdownPromise;
+ }
+}
+var PostHogFetchHttpError, PostHogFetchNetworkError, applyCallerFeatureFlagOverrides = (target, callerProperties) => {
+ for (const key of Object.keys(callerProperties))
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
+ target[key] = callerProperties[key];
+}, OTLP_MAX_BODY_BYTES = 10485760, DEFAULT_QUEUE_ROUTE = "default";
+var init_posthog_core_stateless = __esm(() => {
+ init_eventemitter();
+ init_featureFlagUtils();
+ init_gzip();
+ init_types7();
+ init_utils();
+ init_retry_after();
+ init_uuidv7();
+ init_error_tracking();
+ PostHogFetchHttpError = class PostHogFetchHttpError extends Error {
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
+ }
+ get status() {
+ return this.response.status;
+ }
+ get retryAfterMs() {
+ try {
+ return parseRetryAfterMs(this.response.headers?.get("retry-after"));
+ } catch {
+ return;
+ }
+ }
+ get bodyReadTimedOut() {
+ return this._bodyReadTimedOut;
+ }
+ get text() {
+ if (!this.responseBodyTextPromise)
+ if (Date.now() >= this.responseBodyDeadline) {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ this.cancelResponseBody(timeoutError);
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
+ } else {
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
+ this.responseBodyTimer = safeSetTimeout(() => {
+ this._bodyReadTimedOut = true;
+ const timeoutError = createNamedError("AbortError", "Response body read timed out");
+ reject(timeoutError);
+ this.cancelResponseBody(timeoutError);
+ }, this.responseBodyDeadline - Date.now());
+ });
+ let responseBodyText;
+ try {
+ responseBodyText = Promise.resolve(this.response.text());
+ } catch (error) {
+ responseBodyText = Promise.reject(error);
+ }
+ this.responseBodyTextPromise = Promise.race([
+ responseBodyText,
+ responseBodyTimeout
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
+ }
+ return this.responseBodyTextPromise;
+ }
+ get json() {
+ return this.text.then((text) => JSON.parse(text));
+ }
+ cancelResponseBody(reason) {
+ clearTimeout(this.responseBodyTimer);
+ if (!this.abortController.signal.aborted)
+ this.abortController.abort(reason);
+ (async () => {
+ try {
+ await this.response.body?.cancel();
+ } catch {}
+ })();
+ }
+ };
+ PostHogFetchNetworkError = class PostHogFetchNetworkError extends Error {
+ constructor(error) {
+ super("Network error while fetching PostHog", error instanceof Error ? {
+ cause: error
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+ }
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core.mjs
+var init_posthog_core = __esm(() => {
+ init_featureFlagUtils();
+ init_types7();
+ init_posthog_core_stateless();
+ init_uuidv7();
+ init_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/tracing-headers.mjs
+var init_tracing_headers = __esm(() => {
+ init_type_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.mjs
+function isTruthyOrFalsyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return true;
+ if (typeof value == "string") {
+ const lowercaseValue = value.toLowerCase();
+ return lowercaseValue === "true" || lowercaseValue === "false";
+ }
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyOrFalsyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function isTruthyPropertyValue(value) {
+ if (typeof value == "boolean")
+ return value;
+ if (typeof value == "string")
+ return value.toLowerCase() === "true";
+ if (!Array.isArray(value))
+ return false;
+ for (let index = 0;index < value.length; index++)
+ if (!isTruthyPropertyValue(index in value ? value[index] : null))
+ return false;
+ return true;
+}
+function assertUnicodeScalarString(value) {
+ for (let index = 0;index < value.length; index++) {
+ const unit = value.charCodeAt(index);
+ if (unit >= 55296 && unit <= 56319) {
+ const next = value.charCodeAt(index + 1);
+ if (index + 1 >= value.length || next < 56320 || next > 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ index++;
+ } else if (unit >= 56320 && unit <= 57343)
+ throw new InconclusiveMatchError("Cannot stringify an unpaired surrogate like the flags service");
+ }
+}
+function assertJsonRepresentable(value, seen = new Set) {
+ if (value === null || typeof value == "boolean")
+ return;
+ if (typeof value == "string")
+ return void assertUnicodeScalarString(value);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot represent non-finite number ${value} like the flags service`);
+ return;
+ }
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular array during local evaluation");
+ seen.add(value);
+ try {
+ for (let index = 0;index < value.length; index++)
+ if (index in value)
+ assertJsonRepresentable(value[index], seen);
+ } finally {
+ seen.delete(value);
+ }
+ return;
+ }
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot represent a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot represent a circular object during local evaluation");
+ seen.add(value);
+ try {
+ for (const key of Object.keys(value)) {
+ assertUnicodeScalarString(key);
+ assertJsonRepresentable(value[key], seen);
+ }
+ } finally {
+ seen.delete(value);
+ }
+ return;
+ }
+ throw new InconclusiveMatchError(`Cannot represent ${typeof value} like the flags service`);
+}
+function compareJsonObjectKeys(left, right) {
+ let leftIndex = 0;
+ let rightIndex = 0;
+ while (leftIndex < left.length && rightIndex < right.length) {
+ const leftUnit = left.charCodeAt(leftIndex);
+ const rightUnit = right.charCodeAt(rightIndex);
+ const leftIsHighSurrogate = leftUnit >= 55296 && leftUnit <= 56319;
+ const rightIsHighSurrogate = rightUnit >= 55296 && rightUnit <= 56319;
+ const leftNext = leftIsHighSurrogate ? left.charCodeAt(leftIndex + 1) : 0;
+ const rightNext = rightIsHighSurrogate ? right.charCodeAt(rightIndex + 1) : 0;
+ const leftCodePoint = leftIsHighSurrogate ? (leftUnit - 55296) * 1024 + leftNext - 56320 + 65536 : leftUnit;
+ const rightCodePoint = rightIsHighSurrogate ? (rightUnit - 55296) * 1024 + rightNext - 56320 + 65536 : rightUnit;
+ if (leftCodePoint !== rightCodePoint)
+ return leftCodePoint - rightCodePoint;
+ leftIndex += leftIsHighSurrogate ? 2 : 1;
+ rightIndex += rightIsHighSurrogate ? 2 : 1;
+ }
+ return left.length - right.length;
+}
+function serializeJsonValue(value, seen = new Set) {
+ if (value === null)
+ return "null";
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return JSON.stringify(value);
+ }
+ if (typeof value == "boolean")
+ return value ? "true" : "false";
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ throw new InconclusiveMatchError(`Cannot stringify non-finite number ${value} like the flags service`);
+ if (Number.isInteger(value))
+ throw new InconclusiveMatchError(`Cannot distinguish integer ${value} from an integral JSON float during local evaluation`);
+ return String(value);
+ }
+ if (Array.isArray(value)) {
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular array during local evaluation");
+ seen.add(value);
+ try {
+ const items = [];
+ for (let index = 0;index < value.length; index++)
+ items.push(index in value ? serializeJsonValue(value[index], seen) : "null");
+ return `[${items.join(",")}]`;
+ } finally {
+ seen.delete(value);
+ }
+ }
+ if (typeof value == "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null)
+ throw new InconclusiveMatchError("Cannot stringify a non-JSON object like the flags service");
+ if (seen.has(value))
+ throw new InconclusiveMatchError("Cannot stringify a circular object during local evaluation");
+ seen.add(value);
+ try {
+ const keys = Object.keys(value);
+ keys.forEach(assertUnicodeScalarString);
+ return `{${keys.sort(compareJsonObjectKeys).map((key) => `${JSON.stringify(key)}:${serializeJsonValue(value[key], seen)}`).join(",")}}`;
+ } finally {
+ seen.delete(value);
+ }
+ }
+ throw new InconclusiveMatchError(`Cannot stringify ${typeof value} like the flags service`);
+}
+function exactMatchString(value) {
+ if (typeof value == "string") {
+ assertUnicodeScalarString(value);
+ return value;
+ }
+ return serializeJsonValue(value);
+}
+function isValidRegex(regex) {
+ try {
+ new RegExp(regex);
+ return true;
+ } catch {
+ return false;
+ }
+}
+function asciiLowercase(value) {
+ return String(value).replace(/[A-Z]/g, (character) => character.toLowerCase());
+}
+function parseSemverNumericIdentifier(part, raw, parsingPolicy) {
+ if (!/^\d+$/.test(part) || parsingPolicy === "strict" && part.length > 1 && part[0] === "0")
+ throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
+ return parseInt(part, 10);
+}
+function parseFeatureFlagSemver(value, parsingPolicy = "strict") {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const baseVersion = text.split("-")[0].split("+")[0];
+ if (!baseVersion || baseVersion.startsWith("."))
+ throw new InconclusiveMatchError(`Invalid semver: ${value}`);
+ const parts = baseVersion.split(".");
+ const parsePart = (part) => {
+ if (part === undefined || part === "")
+ return 0;
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
+ };
+ return [
+ parsePart(parts[0]),
+ parsePart(parts[1]),
+ parsePart(parts[2])
+ ];
+}
+function compareSemverTuples(a, b) {
+ for (let i = 0;i < 3; i++) {
+ if (a[i] < b[i])
+ return -1;
+ if (a[i] > b[i])
+ return 1;
+ }
+ return 0;
+}
+function computeTildeBounds(value, parsingPolicy) {
+ const parsed = parseFeatureFlagSemver(value, parsingPolicy);
+ return {
+ lower: [
+ parsed[0],
+ parsed[1],
+ parsed[2]
+ ],
+ upper: [
+ parsed[0],
+ parsed[1] + 1,
+ 0
+ ]
+ };
+}
+function computeCaretBounds(value, parsingPolicy) {
+ const [major, minor, patch] = parseFeatureFlagSemver(value, parsingPolicy);
+ const lower = [
+ major,
+ minor,
+ patch
+ ];
+ let upper;
+ upper = major > 0 ? [
+ major + 1,
+ 0,
+ 0
+ ] : minor > 0 ? [
+ 0,
+ minor + 1,
+ 0
+ ] : [
+ 0,
+ 0,
+ patch + 1
+ ];
+ return {
+ lower,
+ upper
+ };
+}
+function computeWildcardBounds(value, parsingPolicy) {
+ const text = String(value).trim().replace(/^[vV]/, "");
+ const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
+ if (!cleanedText)
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ const parts = cleanedText.split(".");
+ const parseWildcardPart = (part) => {
+ if (parsingPolicy === "legacy-permissive") {
+ const parsed = parseInt(part, 10);
+ if (!isNaN(parsed))
+ return parsed;
+ } else
+ try {
+ return parseSemverNumericIdentifier(part, value, parsingPolicy);
+ } catch {}
+ throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
+ };
+ const major = parseWildcardPart(parts[0]);
+ if (parts.length === 1)
+ return {
+ lower: [
+ major,
+ 0,
+ 0
+ ],
+ upper: [
+ major + 1,
+ 0,
+ 0
+ ]
+ };
+ const minor = parseWildcardPart(parts[1]);
+ return {
+ lower: [
+ major,
+ minor,
+ 0
+ ],
+ upper: [
+ major,
+ minor + 1,
+ 0
+ ]
+ };
+}
+function convertToDateTime(value) {
+ if (value instanceof Date)
+ return value;
+ if (typeof value == "string" || typeof value == "number") {
+ const date = new Date(value);
+ if (!isNaN(date.valueOf()))
+ return date;
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
+ }
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
+}
+function relativeDateParseForFeatureFlagMatching(value) {
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
+ const match = value.match(regex);
+ const parsedDt = new Date(new Date().toISOString());
+ if (!match || !match.groups)
+ return null;
+ const number = parseInt(match.groups["number"]);
+ if (number >= 1e4)
+ return null;
+ const interval = match.groups["interval"];
+ if (interval === "h")
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
+ else if (interval === "d")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
+ else if (interval === "w")
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
+ else if (interval === "m")
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
+ else {
+ if (interval !== "y")
+ return null;
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
+ }
+ return parsedDt;
+}
+function matchFeatureFlagProperty(property, propertyValues, options = {}) {
+ const key = property.key;
+ const value = property.value;
+ const operator = property.operator || "exact";
+ const parsingPolicy = options.semverParsingPolicy ?? "strict";
+ const hasProperty = Object.prototype.hasOwnProperty.call(propertyValues, key);
+ if (hasProperty) {
+ if (operator === "is_not_set")
+ return false;
+ else if (operator === "is_set")
+ return true;
+ } else
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
+ const overrideValue = propertyValues[key];
+ if (overrideValue === undefined) {
+ options.warnFunction?.(`Property ${key} cannot have a value of undefined with the ${operator} operator`);
+ return operator === "is_not";
+ }
+ if (overrideValue === null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator) && operator !== "exact" && operator !== "is_not") {
+ options.warnFunction?.(`Property ${key} cannot have a value of null with the ${operator} operator`);
+ return false;
+ }
+ const computeExactMatch = (target, actual) => {
+ if (isTruthyOrFalsyPropertyValue(target)) {
+ assertJsonRepresentable(actual);
+ return isTruthyPropertyValue(target) === isTruthyPropertyValue(actual);
+ }
+ if (Array.isArray(target)) {
+ const actualString = exactMatchString(actual).toLowerCase();
+ return target.some((item) => exactMatchString(item).toLowerCase() === actualString);
+ }
+ return exactMatchString(target).toLowerCase() === exactMatchString(actual).toLowerCase();
+ };
+ const compare = (lhs, rhs, comparisonOperator) => {
+ if (comparisonOperator === "gt")
+ return lhs > rhs;
+ if (comparisonOperator === "gte")
+ return lhs >= rhs;
+ if (comparisonOperator === "lt")
+ return lhs < rhs;
+ if (comparisonOperator === "lte")
+ return lhs <= rhs;
+ throw new Error(`Invalid operator: ${comparisonOperator}`);
+ };
+ switch (operator) {
+ case "exact":
+ return computeExactMatch(value, overrideValue);
+ case "is_not":
+ return !computeExactMatch(value, overrideValue);
+ case "is_set":
+ return true;
+ case "icontains":
+ return asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "not_icontains":
+ return !asciiLowercase(overrideValue).includes(asciiLowercase(value));
+ case "starts_with":
+ return asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "not_starts_with":
+ return !asciiLowercase(overrideValue).startsWith(asciiLowercase(value));
+ case "ends_with":
+ return asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "not_ends_with":
+ return !asciiLowercase(overrideValue).endsWith(asciiLowercase(value));
+ case "regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
+ case "not_regex":
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
+ case "gt":
+ case "gte":
+ case "lt":
+ case "lte": {
+ const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
+ const parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : 0 / 0;
+ if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
+ return compare(parsedOverride, parsedValue, operator);
+ return compare(String(overrideValue), String(value), operator);
+ }
+ case "is_date_after":
+ case "is_date_before": {
+ if (typeof value == "boolean")
+ throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
+ if (parsedDate == null)
+ parsedDate = convertToDateTime(value);
+ const overrideDate = convertToDateTime(overrideValue);
+ return operator === "is_date_before" ? overrideDate < parsedDate : overrideDate > parsedDate;
+ }
+ case "semver_eq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) === 0;
+ case "semver_neq":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) !== 0;
+ case "semver_gt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) > 0;
+ case "semver_gte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) >= 0;
+ case "semver_lt":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) < 0;
+ case "semver_lte":
+ return compareSemverTuples(parseFeatureFlagSemver(String(overrideValue), parsingPolicy), parseFeatureFlagSemver(String(value), parsingPolicy)) <= 0;
+ case "semver_tilde": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeTildeBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_caret": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeCaretBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ case "semver_wildcard": {
+ const overrideParsed = parseFeatureFlagSemver(String(overrideValue), parsingPolicy);
+ const { lower, upper } = computeWildcardBounds(String(value), parsingPolicy);
+ return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
+ }
+ default:
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
+ }
+}
+async function hashSHA1(text) {
+ const subtle = globalThis.crypto?.subtle;
+ if (!subtle)
+ throw new Error("SubtleCrypto API not available");
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
+ return Array.from(new Uint8Array(hashBuffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
+}
+async function getFeatureFlagHash(key, bucketingValue, salt = "") {
+ const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
+}
+function getFeatureFlagVariantLookupTable(variants) {
+ const table = [];
+ let valueMin = 0;
+ for (const variant of variants) {
+ const valueMax = valueMin + variant.rollout_percentage / 100;
+ table.push({
+ valueMin,
+ valueMax,
+ key: variant.key
+ });
+ valueMin = valueMax;
+ }
+ return table;
+}
+async function getFeatureFlagVariant(key, bucketingValue, variants) {
+ const hashValue = await getFeatureFlagHash(key, bucketingValue, "variant");
+ return getFeatureFlagVariantLookupTable(variants).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax)?.key;
+}
+function resolveFeatureFlagPayload(payloads, flagValue) {
+ if (flagValue === false || flagValue == null || !payloads)
+ return null;
+ const payloadKey = typeof flagValue == "boolean" ? flagValue.toString() : flagValue;
+ const payload = payloads[payloadKey] || null;
+ return payload == null ? null : parsePayload(payload);
+}
+var NULL_VALUES_ALLOWED_OPERATORS, LONG_SCALE = 1152921504606847000, InconclusiveMatchError;
+var init_featureFlagLocalEvaluation = __esm(() => {
+ init_featureFlagUtils();
+ NULL_VALUES_ALLOWED_OPERATORS = [
+ "is_not",
+ "is_set"
+ ];
+ InconclusiveMatchError = class InconclusiveMatchError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = this.constructor.name;
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
+ }
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-any-value.mjs
+function newState() {
+ return {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ };
+}
+function toOtlpKeyValueList(attrs, logger) {
+ try {
+ return encodeKeyValueList(attrs, logger, newState(), 0);
+ } catch {
+ return [];
+ }
+}
+function encodeBigInt(value, logger) {
+ const decimal = value.toString();
+ const limit = BigInt(INT64_RANGE_LIMIT_DECIMAL);
+ if (value >= limit || value < -limit) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
+ };
+ }
+ return {
+ intValue: decimal
+ };
+}
+function encodeAnyValue(value, logger, state, depth) {
+ if (state.remainingNodes <= 0)
+ return {
+ stringValue: TRUNCATED_VALUE
+ };
+ state.remainingNodes--;
+ if (isBoolean(value))
+ return {
+ boolValue: value
+ };
+ if (typeof value == "bigint")
+ return encodeBigInt(value, logger);
+ if (typeof value == "number") {
+ if (!Number.isFinite(value))
+ return {
+ stringValue: String(value)
+ };
+ if (Number.isInteger(value)) {
+ if (Number.isSafeInteger(value))
+ return {
+ intValue: String(value)
+ };
+ if ("u" < typeof BigInt)
+ return {
+ stringValue: String(value)
+ };
+ const decimal = BigInt(value).toString();
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
+ return {
+ stringValue: decimal
+ };
+ }
+ return {
+ intValue: decimal
+ };
+ }
+ return {
+ doubleValue: value
+ };
+ }
+ if (typeof value == "string")
+ return {
+ stringValue: sanitizeString(value)
+ };
+ if (typeof value == "function")
+ return {
+ stringValue: FUNCTION_VALUE
+ };
+ if (typeof value == "symbol")
+ return {
+ stringValue: String(value)
+ };
+ if (typeof value == "object" && value !== null) {
+ if (state.ancestors.has(value))
+ return {
+ stringValue: CIRCULAR_VALUE
+ };
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return {
+ stringValue: TRUNCATED_VALUE
+ };
+ if (value instanceof Date) {
+ const time = value.getTime();
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
+ return {
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
+ };
+ }
+ state.ancestors.add(value);
+ try {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
+ return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
+ } catch {}
+ if (isArray(value))
+ return {
+ arrayValue: {
+ values: encodeArrayValues(value, logger, state, depth + 1)
+ }
+ };
+ return {
+ kvlistValue: {
+ values: encodeKeyValueList(value, logger, state, depth + 1)
+ }
+ };
+ } finally {
+ state.ancestors.delete(value);
+ }
+ }
+ return {
+ stringValue: sanitizeString(String(value))
+ };
+}
+function encodeArrayValues(values, logger, state, depth) {
+ const result = [];
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ let index = 0;
+ for (;index < itemCount && state.remainingNodes > 0; index++)
+ try {
+ const element = index in values ? values[index] : undefined;
+ if (isNullish(element))
+ continue;
+ result.push(encodeAnyValue(element, logger, state, depth));
+ } catch {
+ result.push({
+ stringValue: UNSERIALIZABLE_VALUE
+ });
+ }
+ if (values.length > index)
+ result.push({
+ stringValue: TRUNCATED_VALUE
+ });
+ return result;
+}
+function encodeKeyValueList(attrs, logger, state, depth) {
+ const result = [];
+ for (const key in attrs)
+ if (propertyIsEnumerable.call(attrs, key)) {
+ if (!key) {
+ logger?.debug("Dropping an attribute with an empty key");
+ continue;
+ }
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
+ logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
+ break;
+ }
+ try {
+ const value = attrs[key];
+ if (isNull(value) || isUndefined(value))
+ continue;
+ result.push({
+ key: sanitizeString(key),
+ value: encodeAnyValue(value, logger, state, depth)
+ });
+ } catch {
+ result.push({
+ key: sanitizeString(key),
+ value: {
+ stringValue: UNSERIALIZABLE_VALUE
+ }
+ });
+ }
+ }
+ return result;
+}
+var INT64_RANGE_LIMIT = 9223372036854776000, INT64_RANGE_LIMIT_DECIMAL = "9223372036854775808", propertyIsEnumerable;
+var init_otlp_any_value = __esm(() => {
+ init_type_utils();
+ init_json_utils();
+ propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/otlp-resource.mjs
+function buildOtlpResourceAttributes(config, sdkName, sdkVersion) {
+ return {
+ ...assignUserAttributes({}, config.resourceAttributes),
+ "service.name": config.serviceName || "unknown_service",
+ ...config.environment && {
+ "deployment.environment": config.environment
+ },
+ ...config.serviceVersion && {
+ "service.version": config.serviceVersion
+ },
+ "telemetry.sdk.name": sdkName,
+ "telemetry.sdk.version": sdkVersion
+ };
+}
+function toOtlpResourceKeyValueList(attributes, logger) {
+ const user = assignUserAttributes({}, attributes);
+ const sdk = {};
+ for (const key of SDK_RESOURCE_KEYS)
+ if (Object.prototype.hasOwnProperty.call(user, key)) {
+ sdk[key] = user[key];
+ delete user[key];
+ }
+ return [
+ ...toOtlpKeyValueList(user, logger),
+ ...toOtlpKeyValueList(sdk, logger)
+ ];
+}
+function normalizeOsName(name) {
+ if (!name)
+ return;
+ return Object.prototype.hasOwnProperty.call(OS_NAMES, name) ? OS_NAMES[name] : name;
+}
+function osResourceAttributes(name, version) {
+ const osName = normalizeOsName(name);
+ return {
+ ...osName ? {
+ "os.name": osName
+ } : {},
+ ...version ? {
+ "os.version": version
+ } : {}
+ };
+}
+var SDK_RESOURCE_KEYS, OS_NAMES;
+var init_otlp_resource = __esm(() => {
+ init_json_utils();
+ init_otlp_any_value();
+ SDK_RESOURCE_KEYS = [
+ "service.name",
+ "deployment.environment",
+ "service.version",
+ "telemetry.sdk.name",
+ "telemetry.sdk.version"
+ ];
+ OS_NAMES = {
+ darwin: "macOS",
+ win32: "Windows",
+ cygwin: "Windows",
+ linux: "Linux",
+ android: "Android",
+ freebsd: "FreeBSD",
+ openbsd: "OpenBSD",
+ netbsd: "NetBSD",
+ sunos: "SunOS",
+ aix: "AIX",
+ haiku: "Haiku",
+ "Mac OS X": "macOS"
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/logs-utils.mjs
+var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY;
+var init_logs_utils = __esm(() => {
+ init_utils();
+ init_json_utils();
+ init_otlp_any_value();
+ init_otlp_resource();
+ OTLP_SEVERITY_MAP = {
+ trace: {
+ text: "TRACE",
+ number: 1
+ },
+ debug: {
+ text: "DEBUG",
+ number: 5
+ },
+ info: {
+ text: "INFO",
+ number: 9
+ },
+ warn: {
+ text: "WARN",
+ number: 13
+ },
+ error: {
+ text: "ERROR",
+ number: 17
+ },
+ fatal: {
+ text: "FATAL",
+ number: 21
+ }
+ };
+ DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/flush-timer.mjs
+class FlushTimer {
+ constructor(_onFire) {
+ this._onFire = _onFire;
+ this._firesAt = 0;
+ }
+ get pending() {
+ return !!this._timer;
+ }
+ arm(delayMs) {
+ this.clear();
+ this._firesAt = Date.now() + delayMs;
+ this._timer = safeSetTimeout(() => {
+ this._timer = undefined;
+ this._onFire();
+ }, delayMs);
+ }
+ armNoEarlierThan(delayMs) {
+ if (this._timer && Date.now() + delayMs <= this._firesAt)
+ return;
+ this.arm(delayMs);
+ }
+ clear() {
+ if (this._timer) {
+ clearTimeout(this._timer);
+ this._timer = undefined;
+ }
+ }
+}
+var init_flush_timer = __esm(() => {
+ init_utils();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/utils/backoff.mjs
+function drawJitter() {
+ return 1 - JITTER + Math.random() * JITTER * 2;
+}
+function backoffDelayMs(baseMs, failures, jitter, maxMs) {
+ const exponent = Math.min(Math.max(0, failures - 1), MAX_FLUSH_BACKOFF_EXPONENT);
+ const delay = baseMs * 2 ** exponent;
+ const capped = maxMs === undefined ? delay : Math.min(delay, Math.max(maxMs, baseMs));
+ return Math.round(capped * jitter);
+}
+var MAX_FLUSH_BACKOFF_EXPONENT = 6, MAX_FLUSH_BACKOFF_MS = 30000, JITTER = 0.25, NO_JITTER = 1;
+var init_backoff = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/logs/index.mjs
+var init_logs = __esm(() => {
+ init_logs_utils();
+ init_types7();
+ init_utils();
+ init_flush_timer();
+ init_retry_after();
+ init_backoff();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
+function msToUnixNano(ms) {
+ return String(ms) + "000000";
+}
+function seriesKey(type, name, unit, attributes) {
+ let attrsKey = "";
+ if (attributes) {
+ const keys = Object.keys(attributes).sort();
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
+ }
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
+}
+function bucketIndexFor(value, bounds) {
+ for (let i = 0;i < bounds.length; i++)
+ if (value <= bounds[i])
+ return i;
+ return bounds.length;
+}
+function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
+ return buildOtlpResourceAttributes(config, scopeName, scopeVersion);
+}
+function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
+ return {
+ resourceMetrics: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes)
+ },
+ scopeMetrics: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ metrics
+ }
+ ]
+ }
+ ]
+ };
+}
+var DEFAULT_HISTOGRAM_BOUNDS;
+var init_metrics_utils = __esm(() => {
+ init_otlp_resource();
+ DEFAULT_HISTOGRAM_BOUNDS = [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 75,
+ 100,
+ 250,
+ 500,
+ 750,
+ 1000,
+ 2500,
+ 5000,
+ 7500,
+ 1e4
+ ];
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/config.mjs
+function resolveMetricsConfig(config) {
+ const resourceAttributes = config?.resourceAttributes;
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSend: config?.beforeSend,
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
+ };
+}
+var DEFAULT_FLUSH_INTERVAL_MS = 1e4, DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
+var init_config2 = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/metrics/index.mjs
+class PostHogMetrics {
+ constructor(_instance, _config, _logger) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._series = new Map;
+ this._flushTimer = new FlushTimer(() => this.flush().catch((e) => {
+ this._logger.error("Metrics flush failed:", e);
+ }));
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ this._retryAfter = new RetryAfterWindow;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._generation = 0;
+ }
+ count(name, value = 1, options) {
+ this._capture({
+ name,
+ type: "count",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
+ });
+ }
+ gauge(name, value, options) {
+ this._capture({
+ name,
+ type: "gauge",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
+ });
+ }
+ histogram(name, value, options) {
+ this._capture({
+ name,
+ type: "histogram",
+ value,
+ unit: options?.unit,
+ attributes: options?.attributes
+ });
+ }
+ flush() {
+ const prev = this._flushPromise;
+ const run = async () => {
+ if (prev)
+ await prev.catch(() => {});
+ await this._doFlush();
+ };
+ const p = run().finally(() => {
+ if (this._flushPromise === p)
+ this._flushPromise = null;
+ });
+ this._flushPromise = p;
+ return p;
+ }
+ drainWindow() {
+ if (this._series.size === 0)
+ return null;
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ return this._buildPayload(window);
+ }
+ reset() {
+ this._generation++;
+ this._retryAfter.reset();
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._flushTimer.clear();
+ this._series = new Map;
+ this._flushPromise = null;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ }
+ _capture(sample) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return;
+ const filtered = this._runBeforeSend(sample);
+ if (filtered === null)
+ return;
+ if (!filtered.name || typeof filtered.name != "string")
+ return void this._logger.warn("Dropping metric with empty name");
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
+ if (filtered.type === "count" && filtered.value < 0)
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
+ let attributes;
+ let key;
+ try {
+ attributes = filtered.attributes ? {
+ ...filtered.attributes
+ } : undefined;
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
+ } catch (e) {
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
+ return;
+ }
+ let state = this._series.get(key);
+ if (!state) {
+ if (!this._admitNewSeries())
+ return;
+ state = {
+ name: filtered.name,
+ type: filtered.type,
+ unit: filtered.unit,
+ attributes,
+ windowStartMs: Date.now()
+ };
+ this._series.set(key, state);
+ }
+ const seenType = this._typeByName.get(filtered.name);
+ if (seenType === undefined)
+ this._typeByName.set(filtered.name, filtered.type);
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
+ this._typeCollisionWarned.add(filtered.name);
+ this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
+ }
+ this._fold(state, filtered.value);
+ this._armFlushTimer();
+ }
+ _admitNewSeries() {
+ if (this._series.size < this._config.maxSeriesPerFlush)
+ return true;
+ if (!this._seriesCapWarned) {
+ this._seriesCapWarned = true;
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
+ }
+ return false;
+ }
+ _fold(state, value) {
+ switch (state.type) {
+ case "count":
+ state.total = (state.total ?? 0) + value;
+ break;
+ case "gauge":
+ state.last = value;
+ break;
+ case "histogram": {
+ if (!state.hist)
+ state.hist = {
+ count: 0,
+ sum: 0,
+ min: value,
+ max: value,
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
+ };
+ const hist = state.hist;
+ hist.count += 1;
+ hist.sum += value;
+ hist.min = Math.min(hist.min, value);
+ hist.max = Math.max(hist.max, value);
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
+ break;
+ }
+ }
+ }
+ _runBeforeSend(sample) {
+ const beforeSend = this._config.beforeSend;
+ if (!beforeSend)
+ return sample;
+ const fns = isArray(beforeSend) ? beforeSend : [
+ beforeSend
+ ];
+ let result = sample;
+ for (const fn of fns)
+ try {
+ const next = fn(result);
+ if (!next) {
+ this._logger.info("Metric was rejected in beforeSend function");
+ return null;
+ }
+ result = next;
+ } catch (e) {
+ this._logger.error("Error in beforeSend function for metric:", e);
+ return null;
+ }
+ return result;
+ }
+ _armFlushTimer() {
+ if (this._flushTimer.pending)
+ return;
+ this._flushTimer.arm(this._nextFlushDelay());
+ }
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
+ }
+ async _doFlush() {
+ this._flushTimer.clear();
+ if (this._series.size === 0)
+ return;
+ const window = this._series;
+ this._series = new Map;
+ this._seriesCapWarned = false;
+ this._typeByName = new Map;
+ this._typeCollisionWarned = new Set;
+ const generation = this._generation;
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
+ if (generation !== this._generation)
+ return;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ } else {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ }
+ if (this._flushTimer.pending)
+ this._flushTimer.arm(this._nextFlushDelay());
+ switch (outcome.kind) {
+ case "ok":
+ return;
+ case "retry-later":
+ this._mergeWindowBack(window);
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ return;
+ case "too-large":
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
+ return;
+ case "fatal":
+ this._logger.error("Failed to send metrics batch:", outcome.error);
+ return;
+ }
+ }
+ _buildPayload(window) {
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
+ }
+ _buildMetrics(window) {
+ const nowNano = msToUnixNano(Date.now());
+ const byMetric = new Map;
+ for (const state of window.values()) {
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
+ let metric = byMetric.get(metricKey);
+ if (!metric) {
+ metric = {
+ name: state.name,
+ ...state.unit && {
+ unit: state.unit
+ }
+ };
+ if (state.type === "count")
+ metric.sum = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ isMonotonic: true,
+ dataPoints: []
+ };
+ else if (state.type === "gauge")
+ metric.gauge = {
+ dataPoints: []
+ };
+ else
+ metric.histogram = {
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
+ dataPoints: []
+ };
+ byMetric.set(metricKey, metric);
+ }
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
+ const startNano = msToUnixNano(state.windowStartMs);
+ if (state.type === "count") {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ asDouble: state.total ?? 0
+ };
+ metric.sum.dataPoints.push(dp);
+ } else if (state.type === "gauge") {
+ const dp = {
+ attributes,
+ timeUnixNano: nowNano,
+ asDouble: state.last ?? 0
+ };
+ metric.gauge.dataPoints.push(dp);
+ } else if (state.hist) {
+ const dp = {
+ attributes,
+ startTimeUnixNano: startNano,
+ timeUnixNano: nowNano,
+ count: state.hist.count,
+ sum: state.hist.sum,
+ min: state.hist.min,
+ max: state.hist.max,
+ bucketCounts: state.hist.bucketCounts,
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
+ };
+ metric.histogram.dataPoints.push(dp);
+ }
+ }
+ return Array.from(byMetric.values());
+ }
+ _mergeWindowBack(window) {
+ for (const [key, old] of window) {
+ const current = this._series.get(key);
+ if (!current) {
+ if (this._admitNewSeries())
+ this._series.set(key, old);
+ continue;
+ }
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
+ switch (current.type) {
+ case "count":
+ current.total = (current.total ?? 0) + (old.total ?? 0);
+ break;
+ case "gauge":
+ break;
+ case "histogram":
+ if (old.hist)
+ if (current.hist) {
+ current.hist.count += old.hist.count;
+ current.hist.sum += old.hist.sum;
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
+ } else
+ current.hist = old.hist;
+ break;
+ }
+ }
+ }
+}
+var OTLP_TEMPORALITY_DELTA = 1;
+var init_metrics = __esm(() => {
+ init_utils();
+ init_flush_timer();
+ init_retry_after();
+ init_backoff();
+ init_otlp_any_value();
+ init_metrics_utils();
+ init_config2();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/ids.mjs
+function getRandomBytes(byteLength) {
+ const bytes = new Uint8Array(byteLength);
+ const cryptoLike = globalThis.crypto;
+ if (cryptoLike && typeof cryptoLike.getRandomValues == "function")
+ try {
+ cryptoLike.getRandomValues(bytes);
+ return bytes;
+ } catch {}
+ for (let i = 0;i < byteLength; i++)
+ bytes[i] = Math.floor(256 * Math.random());
+ return bytes;
+}
+function bytesToHex(bytes) {
+ let hex = "";
+ for (let i = 0;i < bytes.length; i++)
+ hex += bytes[i].toString(16).padStart(2, "0");
+ return hex;
+}
+function randomHexId(byteLength) {
+ const hex = bytesToHex(getRandomBytes(byteLength));
+ return /[^0]/.test(hex) ? hex : hex.slice(0, -1) + "1";
+}
+function newTraceId() {
+ return randomHexId(TRACE_ID_BYTES);
+}
+function newSpanId() {
+ return randomHexId(SPAN_ID_BYTES);
+}
+function isValidHexId(value, length, invalid) {
+ return typeof value == "string" && value.length === length && value !== invalid && HEX_RE.test(value);
+}
+function isValidTraceId(value) {
+ return isValidHexId(value, TRACE_ID_HEX, INVALID_TRACE_ID);
+}
+function isValidSpanId(value) {
+ return isValidHexId(value, SPAN_ID_HEX, INVALID_SPAN_ID);
+}
+var TRACE_ID_BYTES = 16, SPAN_ID_BYTES = 8, TRACE_ID_HEX, SPAN_ID_HEX, INVALID_TRACE_ID, INVALID_SPAN_ID, HEX_RE;
+var init_ids = __esm(() => {
+ TRACE_ID_HEX = 2 * TRACE_ID_BYTES;
+ SPAN_ID_HEX = 2 * SPAN_ID_BYTES;
+ INVALID_TRACE_ID = "0".repeat(TRACE_ID_HEX);
+ INVALID_SPAN_ID = "0".repeat(SPAN_ID_HEX);
+ HEX_RE = /^[0-9a-f]+$/;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/traceparent.mjs
+function parseTraceparent(value) {
+ const fields = matchTraceparent(value);
+ return fields && {
+ traceId: fields.traceId,
+ spanId: fields.spanId,
+ flags: definedFlags(fields.flags)
+ };
+}
+function definedFlags(flags) {
+ return 1 & parseInt(flags, 16) ? TRACE_FLAGS_SAMPLED : TRACE_FLAGS_UNSAMPLED;
+}
+function matchTraceparent(value) {
+ if (typeof value != "string")
+ return;
+ const match = TRACEPARENT_RE.exec(value.trim());
+ if (!match)
+ return;
+ const [, version, traceId, spanId, flags, trailing] = match;
+ if (version === "ff")
+ return;
+ if (version === "00" && trailing)
+ return;
+ if (!isValidTraceId(traceId) || !isValidSpanId(spanId))
+ return;
+ return {
+ version,
+ traceId,
+ spanId,
+ flags
+ };
+}
+function normalizeTraceparent(value) {
+ return matchTraceparent(value) && value.trim();
+}
+function traceparentHeader(value) {
+ return Array.isArray(value) && value.length === 1 ? value[0] : value;
+}
+function formatTraceparent(traceId, spanId, flags = TRACE_FLAGS_SAMPLED) {
+ return `00-${traceId}-${spanId}-${flags}`;
+}
+function sanitizeTracestate(value) {
+ if (typeof value != "string")
+ return;
+ const trimmed = value.trim();
+ if (!trimmed)
+ return;
+ if (/[^\x20-\x7e\t]/.test(trimmed))
+ return;
+ const members = trimmed.split(",");
+ if (members.length > TRACESTATE_MAX_MEMBERS)
+ return;
+ for (const member of members)
+ if (member.trim() && !member.includes("="))
+ return;
+ if (trimmed.length <= TRACESTATE_MAX_LENGTH)
+ return trimmed;
+ return trimToLength(members);
+}
+function trimToLength(members) {
+ const kept = [
+ ...members
+ ];
+ const joinedLength = () => kept.reduce((total, member) => total + member.length, 0) + kept.length - 1;
+ for (let index = kept.length - 1;index >= 0 && joinedLength() > TRACESTATE_MAX_LENGTH; index--)
+ if (kept[index].length > TRACESTATE_LARGE_MEMBER_LENGTH)
+ kept.splice(index, 1);
+ while (kept.length && joinedLength() > TRACESTATE_MAX_LENGTH)
+ kept.pop();
+ return kept.length ? kept.join(",") : undefined;
+}
+var TRACEPARENT_RE, TRACE_FLAGS_SAMPLED = "01", TRACE_FLAGS_UNSAMPLED = "00", TRACESTATE_MAX_MEMBERS = 32, TRACESTATE_MAX_LENGTH = 512, TRACESTATE_LARGE_MEMBER_LENGTH = 128;
+var init_traceparent = __esm(() => {
+ init_ids();
+ TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/sanitize.mjs
+function sanitizeName(name, label, maxLength, logger) {
+ if (typeof name == "string" && name.trim())
+ return name.length > maxLength ? name.slice(0, maxLength) : name;
+ logger?.debug(`${label} must be a non-empty string; using "${FALLBACK_SPAN_NAME}"`);
+ return FALLBACK_SPAN_NAME;
+}
+function toEpochMs(value) {
+ if (value == null)
+ return;
+ let ms = value;
+ if (value instanceof Date)
+ try {
+ ms = value.getTime();
+ } catch {
+ return;
+ }
+ if (typeof ms != "number" || !Number.isFinite(ms))
+ return;
+ if (ms < MIN_TIMESTAMP_MS || ms > MAX_TIMESTAMP_MS)
+ return;
+ return ms;
+}
+function resolveStartTime(value, now, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug("Span startTime is out of range or not a valid time; using the current time");
+ return now;
+ }
+ if (now - supplied > DEEP_BACKDATE_WARNING_MS)
+ logger?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp");
+ else if (supplied > now)
+ logger?.debug("Span startTime is in the future; the span may export with a zero duration");
+ return supplied;
+}
+function clampEndTime(endTime, startTime) {
+ return endTime < startTime ? startTime : endTime;
+}
+function resolveSuppliedTime(value, derived, label, logger) {
+ const supplied = toEpochMs(value);
+ if (supplied === undefined) {
+ if (value !== undefined)
+ logger?.debug(`Span ${label} is out of range or not a valid time; using the derived time`);
+ return derived;
+ }
+ return supplied;
+}
+var FALLBACK_SPAN_NAME = "unknown", MAX_TIMESTAMP_MS = 9223372036854, MIN_TIMESTAMP_MS = 0, DEEP_BACKDATE_WARNING_MS = 86400000;
+var init_sanitize = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/span.mjs
+function monotonicNow() {
+ const perf = globalThis.performance;
+ return typeof perf?.now == "function" ? perf.now() : undefined;
+}
+
+class PostHogSpan {
+ constructor(init, _onEnd, _logger) {
+ this._onEnd = _onEnd;
+ this._logger = _logger;
+ this._events = [];
+ this._ended = false;
+ this._userAttributeCount = 0;
+ this._userEventCount = 0;
+ this._droppedAttributes = 0;
+ this._droppedEvents = 0;
+ this._traceId = init.traceId;
+ this._spanId = init.spanId;
+ this._parentSpanId = init.parentSpanId;
+ this._traceState = init.traceState;
+ this._traceFlags = init.traceFlags ?? TRACE_FLAGS_SAMPLED;
+ this._parentIsRemote = init.parentIsRemote ?? false;
+ this._name = init.name;
+ this._kind = init.kind;
+ this._autoKeys = new Set(init.autoAttributeKeys);
+ this._maxAttributes = init.maxAttributes;
+ this._maxEvents = init.maxEvents;
+ this._maxAttributesPerEvent = init.maxAttributesPerEvent;
+ this._maxAttributeValueLength = init.maxAttributeValueLength;
+ this._attributes = Object.create(null);
+ for (const key of Object.keys(init.attributes))
+ this._writeAttribute(key, init.attributes[key]);
+ this._startMono = init.backdated ? undefined : monotonicNow();
+ this._startTime = init.clockAnchor && this._startMono !== undefined ? init.clockAnchor.wall + (this._startMono - init.clockAnchor.mono) : init.startTime;
+ if (this._startMono !== undefined)
+ this._clockAnchor = init.clockAnchor ?? {
+ wall: this._startTime,
+ mono: this._startMono
+ };
+ }
+ _now() {
+ if (this._startMono !== undefined) {
+ const mono = monotonicNow();
+ if (mono !== undefined)
+ return this._startTime + Math.max(0, mono - this._startMono);
+ }
+ return Date.now();
+ }
+ _mutable(operation) {
+ if (this._ended) {
+ this._logger?.debug(`Ignoring ${operation} on a span that has already ended`);
+ return false;
+ }
+ return true;
+ }
+ _writeAttribute(key, value) {
+ if (isNullish(value)) {
+ if (key in this._attributes && !this._autoKeys.has(key))
+ this._userAttributeCount--;
+ delete this._attributes[key];
+ return;
+ }
+ if (!this._autoKeys.has(key) && !(key in this._attributes)) {
+ if (this._userAttributeCount >= this._maxAttributes)
+ return void this._droppedAttributes++;
+ this._userAttributeCount++;
+ }
+ this._attributes[key] = truncateAttributeValue(value, this._maxAttributeValueLength);
+ }
+ setAttribute(key, value) {
+ if (this._mutable("setAttribute"))
+ this._writeAttribute(key, value);
+ return this;
+ }
+ setAttributes(attributes) {
+ if (this._mutable("setAttributes")) {
+ const safe = assignUserAttributes({}, attributes);
+ for (const key of Object.keys(safe))
+ this._writeAttribute(key, safe[key]);
+ }
+ return this;
+ }
+ addEvent(name, attributes, timestamp) {
+ if (this._mutable("addEvent")) {
+ if (this._userEventCount >= this._maxEvents) {
+ this._droppedEvents++;
+ return this;
+ }
+ this._userEventCount++;
+ const bounded = attributes && boundAttributes(attributes, this._maxAttributesPerEvent, this._maxAttributeValueLength);
+ this._events.push({
+ name: sanitizeName(name, "Span event name", this._maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(timestamp, this._now(), "event timestamp", this._logger),
+ ...bounded && {
+ attributes: bounded.attributes,
+ ...bounded.dropped && {
+ droppedAttributesCount: bounded.dropped
+ }
+ }
+ });
+ }
+ return this;
+ }
+ setStatus(status, message) {
+ if (this._mutable("setStatus")) {
+ if (status !== "ok" && status !== "error") {
+ this._logger?.debug(`Ignoring unknown span status "${String(status)}"; expected "ok" or "error"`);
+ return this;
+ }
+ this._status = {
+ code: status,
+ ...message && {
+ message: truncateString(message, this._maxAttributeValueLength)
+ }
+ };
+ }
+ return this;
+ }
+ get statusIsExplicitlyOk() {
+ return this._status?.code === "ok";
+ }
+ recordException(error) {
+ if (!this._mutable("recordException"))
+ return this;
+ const { type, message, stack } = describeError(error);
+ this.addEvent(EXCEPTION_EVENT_NAME, {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
+ }
+ });
+ return this.setStatus("error", message);
+ }
+ updateName(name) {
+ if (this._mutable("updateName"))
+ this._name = sanitizeName(name, "Span name", this._maxAttributeValueLength, this._logger);
+ return this;
+ }
+ traceparent() {
+ return formatTraceparent(this._traceId, this._spanId, this._traceFlags);
+ }
+ tracestate() {
+ return this._traceState ?? null;
+ }
+ childContext() {
+ return {
+ traceId: this._traceId,
+ parentSpanId: this._spanId,
+ traceState: this._traceState,
+ traceFlags: this._traceFlags,
+ clockAnchor: this._clockAnchor
+ };
+ }
+ end(endTime) {
+ if (this._ended)
+ return void this._logger?.debug("Ignoring end() on a span that has already ended");
+ this._ended = true;
+ const derived = this._now();
+ const resolved = resolveSuppliedTime(endTime, derived, "end time", this._logger);
+ this._onEnd({
+ traceId: this._traceId,
+ spanId: this._spanId,
+ ...this._parentSpanId && {
+ parentSpanId: this._parentSpanId
+ },
+ ...this._traceState && {
+ traceState: this._traceState
+ },
+ traceFlags: this._traceFlags,
+ parentIsRemote: this._parentIsRemote,
+ name: this._name,
+ kind: this._kind,
+ ...this._status && {
+ status: this._status
+ },
+ attributes: {
+ ...this._attributes
+ },
+ events: this._events,
+ startTime: this._startTime,
+ endTime: clampEndTime(resolved, this._startTime),
+ ...this._droppedAttributes && {
+ droppedAttributesCount: this._droppedAttributes
+ },
+ ...this._droppedEvents && {
+ droppedEventsCount: this._droppedEvents
+ }
+ }, this._autoKeys);
+ }
+}
+function safeString(value) {
+ try {
+ return typeof value == "string" ? value : String(value);
+ } catch {
+ return UNSERIALIZABLE_VALUE;
+ }
+}
+function nonNegativeCount(value) {
+ if (typeof value != "number" || !Number.isFinite(value) || value <= 0)
+ return 0;
+ return Math.min(Math.floor(value), MAX_UINT32);
+}
+function orderedKeys(attributes, keysBeforeHook) {
+ if (!keysBeforeHook.length)
+ return Object.keys(attributes);
+ const beforeHook = keysBeforeHook.filter((key) => Object.prototype.propertyIsEnumerable.call(attributes, key));
+ const seen = new Set(beforeHook);
+ return [
+ ...beforeHook,
+ ...Object.keys(attributes).filter((key) => !seen.has(key))
+ ];
+}
+function applySpanLimits(record, autoKeys, maxAttributes, maxEvents, maxAttributesPerEvent, maxAttributeValueLength, keysBeforeHook = []) {
+ let kept = 0;
+ let droppedAttributes = 0;
+ const attributes = {};
+ for (const key of orderedKeys(record.attributes, keysBeforeHook)) {
+ const value = record.attributes[key];
+ if (!isNullish(value)) {
+ if (!autoKeys.has(key)) {
+ if (kept >= maxAttributes) {
+ droppedAttributes++;
+ continue;
+ }
+ kept++;
+ }
+ Object.defineProperty(attributes, key, {
+ value: truncateAttributeValue(value, maxAttributeValueLength),
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ }
+ record.attributes = attributes;
+ if (droppedAttributes)
+ record.droppedAttributesCount = nonNegativeCount(record.droppedAttributesCount) + droppedAttributes;
+ let keptEvents = 0;
+ let droppedEvents = 0;
+ const events = [];
+ for (const event of record.events) {
+ if (keptEvents >= maxEvents) {
+ droppedEvents++;
+ continue;
+ }
+ keptEvents++;
+ if (event.attributes) {
+ const bounded = boundAttributes(event.attributes, maxAttributesPerEvent, maxAttributeValueLength);
+ event.attributes = bounded.attributes;
+ if (bounded.dropped)
+ event.droppedAttributesCount = nonNegativeCount(event.droppedAttributesCount) + bounded.dropped;
+ }
+ events.push(event);
+ }
+ record.events = events;
+ if (droppedEvents)
+ record.droppedEventsCount = nonNegativeCount(record.droppedEventsCount) + droppedEvents;
+ if (record.status?.message)
+ record.status = {
+ ...record.status,
+ message: truncateString(safeString(record.status.message), maxAttributeValueLength)
+ };
+}
+
+class NoopSpan {
+ setAttribute() {
+ return this;
+ }
+ setAttributes() {
+ return this;
+ }
+ addEvent() {
+ return this;
+ }
+ setStatus() {
+ return this;
+ }
+ recordException() {
+ return this;
+ }
+ updateName() {
+ return this;
+ }
+ traceparent() {
+ return null;
+ }
+ tracestate() {
+ return null;
+ }
+ end() {}
+}
+function readStack(error) {
+ try {
+ const stack = error.stack;
+ return typeof stack == "string" && stack ? {
+ stack
+ } : {};
+ } catch {
+ return {};
+ }
+}
+function inertSpan(options, active) {
+ const parent = traceparentHeader(options?.parent) ?? active;
+ const inbound = typeof parent == "string" || parent == null ? parent : readHandle(parent, "traceparent");
+ const traceparent = normalizeTraceparent(inbound);
+ if (!traceparent)
+ return NOOP_SPAN;
+ const tracestate = typeof parent == "string" || parent == null ? options?.tracestate : readHandle(parent, "tracestate");
+ return new PassThroughSpan(traceparent, sanitizeTracestate(tracestate));
+}
+function readHandle(parent, method) {
+ try {
+ const fn = parent[method];
+ return typeof fn == "function" ? fn.call(parent) : undefined;
+ } catch {
+ return;
+ }
+}
+function truncateString(value, maxLength) {
+ return value.length > maxLength ? value.slice(0, maxLength) : value;
+}
+function truncateAttributeValue(value, maxLength) {
+ return truncateValue(value, maxLength, {
+ ancestors: new WeakSet,
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
+ }, 0);
+}
+function truncateValue(value, maxLength, state, depth) {
+ if (value === null || typeof value != "object") {
+ if (isNullish(value))
+ return value;
+ if (state.remainingNodes <= 0)
+ return value;
+ state.remainingNodes--;
+ return typeof value == "string" ? truncateString(value, maxLength) : value;
+ }
+ if (state.ancestors.has(value))
+ return CIRCULAR_VALUE;
+ if (state.remainingNodes <= 0 || depth >= MAX_JSON_SAFE_VALUE_DEPTH)
+ return value;
+ state.remainingNodes--;
+ state.ancestors.add(value);
+ try {
+ if (value instanceof Date)
+ return value;
+ const resolved = resolveToJson(value);
+ if (resolved.selfDescribed)
+ return isNullish(resolved.value) ? String(resolved.value) : truncateValue(resolved.value, maxLength, state, depth + 1);
+ if (isArray(value)) {
+ const walked = Math.min(value.length, MAX_JSON_SAFE_VALUE_ITEMS);
+ const boundedItems = [];
+ for (let index = 0;index < walked; index++)
+ try {
+ boundedItems.push(truncateValue(value[index], maxLength, state, depth + 1));
+ } catch {
+ boundedItems.push(UNSERIALIZABLE_VALUE);
+ }
+ if (value.length > walked)
+ boundedItems.length = value.length;
+ return boundedItems;
+ }
+ const bounded = {};
+ let emittable = 0;
+ for (const key of Object.keys(value)) {
+ if (emittable >= MAX_JSON_SAFE_VALUE_ITEMS)
+ break;
+ let boundedItem;
+ try {
+ boundedItem = truncateValue(value[key], maxLength, state, depth + 1);
+ } catch {
+ boundedItem = UNSERIALIZABLE_VALUE;
+ }
+ if (key && !isNullish(boundedItem))
+ emittable++;
+ Object.defineProperty(bounded, key, {
+ value: boundedItem,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ }
+ return bounded;
+ } catch {
+ return value;
+ } finally {
+ state.ancestors.delete(value);
+ }
+}
+function resolveToJson(value) {
+ try {
+ const toJSON = value.toJSON;
+ if (typeof toJSON == "function")
return {
- kind: "fatal",
- error: new Error("The client is disabled")
+ selfDescribed: true,
+ value: toJSON.call(value)
};
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
+ } catch {}
+ return {
+ selfDescribed: false
+ };
+}
+function boundAttributes(source, max, maxLength) {
+ let keys;
+ try {
+ keys = Object.keys(source);
+ } catch {
+ return {
+ attributes: {},
+ dropped: 0
};
+ }
+ const attributes = {};
+ let kept = 0;
+ let dropped = 0;
+ for (const key of keys) {
+ if (kept >= max) {
+ dropped++;
+ continue;
+ }
+ let value;
try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
- }
+ value = truncateAttributeValue(source[key], maxLength);
+ } catch {
+ value = UNSERIALIZABLE_VALUE;
+ }
+ if (!isNullish(value)) {
+ kept++;
+ Object.defineProperty(attributes, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true
});
- return {
- kind: "ok"
- };
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (err instanceof PostHogFetchNetworkError)
- return {
- kind: "retry-later",
- error: err
- };
- return {
- kind: "fatal",
- error: err
- };
}
}
- async _sendMetricsBatch(payload) {
- if (this.disabled)
+ return {
+ attributes,
+ dropped
+ };
+}
+function truncateAttributes(attributes, maxLength) {
+ for (const key of Object.keys(attributes))
+ attributes[key] = truncateAttributeValue(attributes[key], maxLength);
+ return attributes;
+}
+function runWithActiveSpan(contextManager, span, fn) {
+ return span === NOOP_SPAN ? fn(span) : contextManager.with(span, () => fn(span));
+}
+function describeError(error) {
+ try {
+ const stack = readStack(error);
+ if (isError(error))
return {
- kind: "fatal",
- error: new Error("The client is disabled")
+ type: error.name || "Error",
+ message: error.message || "",
+ ...stack
};
- const serialized = JSON.stringify(payload);
- const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
- const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
- const fetchOptions = {
- method: "POST",
- headers: {
- ...this.getCustomHeaders(),
- "Content-Type": "application/json",
- ...gzippedPayload !== null && {
- "Content-Encoding": "gzip"
- }
- },
- body: gzippedPayload || serialized
- };
- try {
- await this.fetchWithRetry(url, fetchOptions, {
- type: "successful-write"
- }, {
- retryCheck: (err) => {
- if (isPostHogFetchContentTooLargeError(err))
- return false;
- return isPostHogFetchRetryableError(err);
- }
- });
+ if (typeof error == "string")
return {
- kind: "ok"
+ type: "string",
+ message: error
};
- } catch (err) {
- if (isPostHogFetchContentTooLargeError(err))
- return {
- kind: "too-large"
- };
- if (isPostHogFetchRetryableError(err))
+ if (error && typeof error == "object") {
+ const maybe = error;
+ if (typeof maybe.message == "string")
return {
- kind: "retry-later",
- error: err
+ type: typeof maybe.name == "string" ? maybe.name : "Object",
+ message: maybe.message,
+ ...stack
};
- return {
- kind: "fatal",
- error: err
+ }
+ return {
+ type: typeof error,
+ message: String(error)
+ };
+ } catch {
+ return {
+ type: typeof error,
+ message: ""
+ };
+ }
+}
+var EXCEPTION_EVENT_NAME = "exception", MAX_UINT32 = 4294967295, NOOP_SPAN, PassThroughSpan;
+var init_span = __esm(() => {
+ init_traceparent();
+ init_sanitize();
+ init_utils();
+ init_json_utils();
+ NOOP_SPAN = /* @__PURE__ */ new NoopSpan;
+ PassThroughSpan = class PassThroughSpan extends NoopSpan {
+ constructor(_traceparent, _tracestate) {
+ super(), this._traceparent = _traceparent, this._tracestate = _tracestate;
+ }
+ traceparent() {
+ return this._traceparent;
+ }
+ tracestate() {
+ return this._tracestate ?? null;
+ }
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/otlp.mjs
+function spanFlags(record) {
+ const traceFlags = parseInt(record.traceFlags, 16);
+ const w3c = Number.isFinite(traceFlags) ? 255 & traceFlags : TRACE_FLAGS_SAMPLED2;
+ return w3c | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE | (record.parentIsRemote ? SPAN_FLAGS_CONTEXT_IS_REMOTE : 0);
+}
+function wireString(value) {
+ if (typeof value == "string")
+ return sanitizeString(value);
+ try {
+ return sanitizeString(String(value));
+ } catch {
+ return UNSERIALIZABLE_VALUE;
+ }
+}
+function spanKindToOtlp(kind) {
+ if (kind && Object.prototype.hasOwnProperty.call(SPAN_KIND_TO_OTLP, kind))
+ return SPAN_KIND_TO_OTLP[kind];
+ return SPAN_KIND_TO_OTLP.internal;
+}
+function msToUnixNanoString(ms) {
+ let whole = Math.floor(ms);
+ let fractionalNanos = Math.round((ms - whole) * 1e6);
+ if (fractionalNanos >= 1e6) {
+ whole += 1;
+ fractionalNanos = 0;
+ }
+ return String(whole) + String(fractionalNanos).padStart(6, "0");
+}
+function toOtlpEvent(event, logger) {
+ const encoded = {
+ name: wireString(event.name),
+ timeUnixNano: msToUnixNanoString(event.timestamp)
+ };
+ if (event.attributes) {
+ const attributes = toOtlpKeyValueList(event.attributes, logger);
+ if (attributes.length)
+ encoded.attributes = attributes;
+ }
+ const dropped = nonNegativeCount(event.droppedAttributesCount);
+ if (dropped)
+ encoded.droppedAttributesCount = dropped;
+ return encoded;
+}
+function buildOtlpSpan(record, logger) {
+ const span = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ name: wireString(record.name),
+ kind: spanKindToOtlp(record.kind),
+ startTimeUnixNano: msToUnixNanoString(record.startTime),
+ endTimeUnixNano: msToUnixNanoString(record.endTime),
+ flags: spanFlags(record)
+ };
+ if (record.parentSpanId)
+ span.parentSpanId = record.parentSpanId;
+ if (record.traceState)
+ span.traceState = wireString(record.traceState);
+ const attributes = toOtlpKeyValueList(record.attributes, logger);
+ if (attributes.length)
+ span.attributes = attributes;
+ if (record.events.length)
+ span.events = record.events.map((event) => toOtlpEvent(event, logger));
+ const droppedAttributes = nonNegativeCount(record.droppedAttributesCount);
+ if (droppedAttributes)
+ span.droppedAttributesCount = droppedAttributes;
+ const droppedEvents = nonNegativeCount(record.droppedEventsCount);
+ if (droppedEvents)
+ span.droppedEventsCount = droppedEvents;
+ if (record.status)
+ span.status = {
+ code: SPAN_STATUS_TO_OTLP[record.status.code],
+ ...record.status.message && {
+ message: wireString(record.status.message)
+ }
+ };
+ return span;
+}
+function buildTracesResourceAttributes(config, sdkName, sdkVersion) {
+ return buildOtlpResourceAttributes(config, sdkName, sdkVersion);
+}
+function buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, logger) {
+ return {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: toOtlpResourceKeyValueList(resourceAttributes, logger)
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: scopeName,
+ version: scopeVersion
+ },
+ spans
+ }
+ ]
+ }
+ ]
+ };
+}
+var SPAN_KIND_TO_OTLP, SPAN_STATUS_TO_OTLP, TRACE_FLAGS_SAMPLED2 = 1, SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE = 256, SPAN_FLAGS_CONTEXT_IS_REMOTE = 512;
+var init_otlp = __esm(() => {
+ init_span();
+ init_otlp_any_value();
+ init_json_utils();
+ init_otlp_resource();
+ SPAN_KIND_TO_OTLP = {
+ internal: 1,
+ server: 2,
+ client: 3,
+ producer: 4,
+ consumer: 5
+ };
+ SPAN_STATUS_TO_OTLP = {
+ ok: 1,
+ error: 2
+ };
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/index.mjs
+function clockNow() {
+ return monotonicNow() ?? Date.now();
+}
+function isOwnSpan(value) {
+ try {
+ return value instanceof PostHogSpan;
+ } catch {
+ return false;
+ }
+}
+function remoteContext(header, tracestate) {
+ const remote = parseTraceparent(header);
+ if (!remote)
+ return;
+ return {
+ traceId: remote.traceId,
+ parentSpanId: remote.spanId,
+ traceState: sanitizeTracestate(tracestate),
+ traceFlags: remote.flags,
+ isRemote: true
+ };
+}
+function looksLikeSpan(value) {
+ try {
+ return typeof value.traceparent == "function";
+ } catch {
+ return false;
+ }
+}
+function isSpanRecordShape(record) {
+ return !!record.attributes && typeof record.attributes == "object" && !Array.isArray(record.attributes) && Array.isArray(record.events) && record.name !== undefined && record.kind !== undefined && record.startTime !== undefined && record.endTime !== undefined;
+}
+function restoreField(record, field, value) {
+ if (record[field] !== value)
+ record[field] = value;
+}
+function withRestoredIdentity(hooked, original) {
+ try {
+ const descriptors = Object.getOwnPropertyDescriptors(hooked);
+ for (const field of [
+ "traceId",
+ "spanId",
+ "parentSpanId",
+ "traceState"
+ ])
+ descriptors[field] = {
+ value: original[field],
+ enumerable: true,
+ writable: true,
+ configurable: true
};
+ return Object.create(Object.getPrototypeOf(hooked), descriptors);
+ } catch {
+ return hooked;
+ }
+}
+
+class PostHogTraces {
+ constructor(_instance, _config, _logger, _getContext, _contextManager, _onSpanQueued) {
+ this._instance = _instance;
+ this._config = _config;
+ this._logger = _logger;
+ this._getContext = _getContext;
+ this._contextManager = _contextManager;
+ this._onSpanQueued = _onSpanQueued;
+ this._queue = [];
+ this._flushTimer = new FlushTimer(() => this._flushInBackground());
+ this._flushPromise = null;
+ this._droppedSinceWarning = 0;
+ this._lastDropWarningAt = 0;
+ this._dropReasons = new Set;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter = new RetryAfterWindow;
+ this._headBatchFailures = 0;
+ this._headBatchSize = 0;
+ this._headBatchChargeableAt = 0;
+ this._generation = 0;
+ this._liveSpans = new Map;
+ this._maxExportBatchSize = _config.maxExportBatchSize;
+ }
+ startSpan(name, options) {
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return inertSpan(options, this._contextManager.active());
+ const explicitParent = traceparentHeader(options?.parent);
+ if (explicitParent && typeof explicitParent != "string" && !isOwnSpan(explicitParent)) {
+ if (looksLikeSpan(explicitParent)) {
+ this._logger.debug("Span parent is not a span from this SDK; returning an inert span");
+ return inertSpan(options, this._contextManager.active());
+ }
+ this._logger.debug("Ignoring an unusable span parent");
+ }
+ const parent = this._resolveParent(explicitParent, options);
+ this._evictAgedSpans();
+ if (this._liveSpans.size >= this._config.maxLiveSpans) {
+ this._recordDrop(1, `the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`);
+ return inertSpan(options, this._contextManager.active());
+ }
+ const now = Date.now();
+ const startTime = resolveStartTime(options?.startTime, now, this._logger);
+ const spanId = newSpanId();
+ this._liveSpans.set(spanId, clockNow());
+ const autoAttributes = this._autoContextAttributes();
+ return new PostHogSpan({
+ traceId: parent?.traceId ?? newTraceId(),
+ spanId,
+ parentSpanId: parent?.parentSpanId,
+ traceState: parent?.traceState,
+ traceFlags: parent?.traceFlags,
+ parentIsRemote: parent?.isRemote,
+ name: sanitizeName(name, "Span name", this._config.maxAttributeValueLength, this._logger),
+ kind: options?.kind ?? "internal",
+ attributes: assignUserAttributes({
+ ...autoAttributes
+ }, options?.attributes),
+ autoAttributeKeys: Object.keys(autoAttributes),
+ maxAttributes: this._config.maxAttributesPerSpan,
+ maxEvents: this._config.maxEventsPerSpan,
+ maxAttributesPerEvent: this._config.maxAttributesPerEvent,
+ maxAttributeValueLength: this._config.maxAttributeValueLength,
+ startTime,
+ backdated: startTime !== now,
+ clockAnchor: toEpochMs(options?.startTime) === undefined ? parent?.clockAnchor : undefined
+ }, (record, autoKeys) => this._onSpanEnd(record, autoKeys), this._logger);
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const span = this.startSpan(name, options);
+ try {
+ const result = runWithActiveSpan(this._contextManager, span, fn);
+ if (isPromise(result))
+ return result.then((value) => {
+ span.end();
+ return value;
+ }, (error) => {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
+ });
+ span.end();
+ return result;
+ } catch (error) {
+ this._recordCallbackError(span, error);
+ span.end();
+ throw error;
}
}
- async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
- const body = options.body ? options.body : "";
- let reqByteLength = -1;
+ getActiveSpan() {
+ return this._contextManager.active() ?? null;
+ }
+ get throttled() {
+ return this._retryAfter.isOpen();
+ }
+ async flush() {
+ for (;; ) {
+ if (!this._queue.length)
+ return;
+ const inFlight = this._flushPromise;
+ const removed = await (inFlight ?? this._startFlush());
+ if (!removed)
+ return;
+ }
+ }
+ _startFlush() {
+ this._flushTimer.clear();
+ const startedAtGeneration = this._generation;
+ const promise = Promise.resolve().then(() => startedAtGeneration === this._generation ? this._flushInner() : 0).finally(() => {
+ if (this._flushPromise === promise)
+ this._flushPromise = null;
+ this._armFlushTimerIfQueuedNoEarlierThan();
+ });
+ this._flushPromise = promise;
+ return promise;
+ }
+ reset() {
+ this._flushTimer.clear();
+ if (this._queue.length)
+ this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`);
+ this._queue = [];
+ this._liveSpans.clear();
+ this._flushPromise = null;
+ this._generation++;
+ this._maxExportBatchSize = this._config.maxExportBatchSize;
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ this._lastDropWarningAt = 0;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._retryAfter.reset();
+ this._resetHeadBatchBudget();
+ }
+ _resetHeadBatchBudget() {
+ this._headBatchFailures = 0;
+ this._headBatchChargeableAt = 0;
+ }
+ _resolveParent(explicit, options) {
+ if (typeof explicit == "string") {
+ const remote = remoteContext(explicit, options?.tracestate);
+ if (!remote)
+ this._logger.debug("Ignoring malformed traceparent; starting a new trace");
+ return remote;
+ }
+ if (isOwnSpan(explicit))
+ return explicit.childContext();
+ const active = this._contextManager.active();
+ if (isOwnSpan(active))
+ return active.childContext();
+ if (active instanceof PassThroughSpan)
+ return remoteContext(active.traceparent(), active.tracestate() ?? undefined);
+ }
+ _autoContextAttributes() {
+ let context;
try {
- reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
- } catch {
- if (body instanceof Blob)
- reqByteLength = body.size;
- else if (body instanceof Uint8Array)
- reqByteLength = body.byteLength;
- else {
- const encoded = new TextEncoder().encode(body);
- reqByteLength = encoded.length;
+ context = this._getContext();
+ } catch (error) {
+ this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes", error);
+ return {};
+ }
+ const attributes = {};
+ if (context.distinctId)
+ attributes.posthogDistinctId = context.distinctId;
+ if (context.sessionId)
+ attributes.sessionId = context.sessionId;
+ if (context.currentUrl)
+ attributes["url.full"] = context.currentUrl;
+ if (context.screenName)
+ attributes["screen.name"] = context.screenName;
+ if (context.appState)
+ attributes["app.state"] = context.appState;
+ return attributes;
+ }
+ _recordCallbackError(span, error) {
+ if (!(span instanceof PostHogSpan))
+ return;
+ const { type, message, stack } = describeError(error);
+ span.addEvent("exception", {
+ "exception.type": type,
+ "exception.message": message,
+ ...stack && {
+ "exception.stacktrace": stack
}
+ });
+ if (!span.statusIsExplicitlyOk)
+ span.setStatus("error", message);
+ }
+ _evictAgedSpans() {
+ const cutoff = clockNow() - this._config.maxSpanAgeMs;
+ let evicted = 0;
+ for (const [spanId, startedAt] of this._liveSpans) {
+ if (startedAt > cutoff)
+ break;
+ this._liveSpans.delete(spanId);
+ evicted++;
}
- const retriableOptions = {
- ...this._retryOptions,
- ...retryOptions
+ if (evicted)
+ this._recordDrop(evicted, `they were still live after ${this._config.maxSpanAgeMs}ms`);
+ }
+ _onSpanEnd(incoming, autoKeys) {
+ if (!this._liveSpans.delete(incoming.spanId))
+ return;
+ if (this._instance.isDisabled || this._instance.optedOut)
+ return void this._recordDrop(1, "the user has opted out");
+ const record = this._runBeforeSpanSend(incoming, autoKeys);
+ if (!record)
+ return;
+ this._reportLimitDrops(record);
+ if (this._queue.length >= this._config.maxQueueSize)
+ return void this._recordDrop(1, `the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);
+ this._queue.push(record);
+ try {
+ this._onSpanQueued?.();
+ } catch (error) {
+ this._logger.debug("Span queue notification failed", error);
+ }
+ if (!(this._queue.length >= this._maxExportBatchSize) || this._consecutiveFlushFailures || this._retryAfter.isOpen())
+ this._armFlushTimerIfQueued();
+ else
+ this._flushInBackground();
+ }
+ _reportLimitDrops(record) {
+ const attributes = record.droppedAttributesCount ?? 0;
+ const events = record.droppedEventsCount ?? 0;
+ let eventAttributes = 0;
+ for (const event of record.events)
+ eventAttributes += event.droppedAttributesCount ?? 0;
+ if (attributes || events || eventAttributes)
+ this._logger.debug(`Span limits discarded data from "${record.name}": ${attributes} attributes, ${events} events, ${eventAttributes} event attributes`);
+ }
+ _runBeforeSpanSend(record, autoKeys) {
+ if (!this._config.beforeSpanSend.length)
+ return record;
+ const identity = {
+ traceId: record.traceId,
+ spanId: record.spanId,
+ parentSpanId: record.parentSpanId,
+ traceState: record.traceState
};
- let attempt = 0;
- return await retriable(async () => {
- attempt++;
- const ctrl = new AbortController;
- const timeoutMs = requestTimeout ?? this.requestTimeout;
- const requestDeadline = Date.now() + timeoutMs;
- let timer;
- const deadline = new Promise((_resolve, reject) => {
- timer = safeSetTimeout(() => {
- const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
- timeoutError.name = "AbortError";
- reject(timeoutError);
- ctrl.abort(timeoutError);
- }, timeoutMs);
- });
- let res;
- let responseAccepted = false;
- let cancellation;
- const cancelBody = () => cancellation ??= (async () => {
- try {
- await res?.body?.cancel();
- } catch {}
- })();
- try {
- let fetchPromise;
- try {
- fetchPromise = this.fetch(url, {
- signal: ctrl.signal,
- ...options
- });
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
- }
- fetchPromise.then((lateResponse) => {
- if (ctrl.signal.aborted && !responseAccepted)
- Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
- }).catch(() => {});
- try {
- res = await Promise.race([
- fetchPromise,
- deadline
- ]);
- responseAccepted = true;
- } catch (e) {
- throw new PostHogFetchNetworkError(e);
- }
- const isNoCors = options.mode === "no-cors";
- if (!isNoCors && (res.status < 200 || res.status >= 400))
- throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
- if (responseHandling.type === "successful-write") {
- try {
- await Promise.race([
- cancelBody(),
- deadline
- ]);
- } catch {}
- return;
- }
- try {
- return await Promise.race([
- responseHandling.consume(res),
- deadline
- ]);
- } catch (e) {
- if (ctrl.signal.aborted)
- throw new PostHogFetchNetworkError(e);
- throw e;
+ const originalTimes = {
+ startTime: record.startTime,
+ endTime: record.endTime
+ };
+ const originalDropped = {
+ attributes: record.droppedAttributesCount,
+ events: record.droppedEventsCount
+ };
+ const keysBeforeHook = Object.keys(record.attributes);
+ const originalPropagation = {
+ traceFlags: record.traceFlags,
+ parentIsRemote: record.parentIsRemote
+ };
+ const originalStatus = record.status && {
+ ...record.status
+ };
+ let hooked = record;
+ let current = record;
+ try {
+ for (const hook of this._config.beforeSpanSend) {
+ const result = hook(hooked);
+ if (!result) {
+ this._recordDrop(1, "beforeSpanSend dropped it");
+ return null;
}
- } finally {
- clearTimeout(timer);
- if (ctrl.signal.aborted && res)
- cancelBody();
+ hooked = this._keepSpanIdentity(result, identity);
+ }
+ const rebuilt = {
+ traceId: identity.traceId,
+ spanId: identity.spanId,
+ parentSpanId: identity.parentSpanId,
+ traceState: identity.traceState,
+ name: hooked.name,
+ kind: hooked.kind,
+ status: hooked.status,
+ attributes: hooked.attributes,
+ events: hooked.events,
+ startTime: hooked.startTime,
+ endTime: hooked.endTime,
+ traceFlags: originalPropagation.traceFlags,
+ parentIsRemote: originalPropagation.parentIsRemote,
+ droppedAttributesCount: originalDropped.attributes,
+ droppedEventsCount: originalDropped.events
+ };
+ current = rebuilt;
+ if (!isSpanRecordShape(current)) {
+ this._logger.debug("beforeSpanSend did not return a span record; dropping the span");
+ this._recordDrop(1, "beforeSpanSend returned an unusable record");
+ return null;
}
- }, {
- ...retriableOptions,
- retryCheck: (error) => {
- const shouldRetry = retriableOptions.retryCheck(error);
- if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
- error.cancelResponseBody();
- return shouldRetry;
+ current.name = sanitizeName(current.name, "Span name", this._config.maxAttributeValueLength, this._logger);
+ if (current.status && current.status.code !== "ok" && current.status.code !== "error") {
+ this._logger.debug("beforeSpanSend set an unknown span status; keeping the original");
+ current.status = originalStatus;
}
- });
+ current.startTime = toEpochMs(current.startTime) ?? originalTimes.startTime;
+ current.endTime = clampEndTime(toEpochMs(current.endTime) ?? originalTimes.endTime, current.startTime);
+ const sanitizedEvents = [];
+ for (const event of current.events)
+ try {
+ sanitizedEvents.push({
+ ...event,
+ name: sanitizeName(event.name, "Span event name", this._config.maxAttributeValueLength, this._logger),
+ timestamp: resolveSuppliedTime(event.timestamp, current.startTime, "event timestamp", this._logger)
+ });
+ } catch {
+ this._logger.debug("beforeSpanSend left an unreadable span event; dropping it");
+ }
+ current.events = sanitizedEvents;
+ applySpanLimits(current, autoKeys, this._config.maxAttributesPerSpan, this._config.maxEventsPerSpan, this._config.maxAttributesPerEvent, this._config.maxAttributeValueLength, keysBeforeHook);
+ return current;
+ } catch (error) {
+ this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed", error);
+ this._recordDrop(1, "beforeSpanSend failed");
+ return null;
+ }
}
- async _shutdown(shutdownTimeoutMs = 30000) {
- await this._initPromise;
- let hasTimedOut = false;
- this.clearFlushTimer();
- if (this.disabled)
+ _keepSpanIdentity(hooked, original) {
+ if (hooked.traceId !== original.traceId || hooked.spanId !== original.spanId || hooked.parentSpanId !== original.parentSpanId)
+ this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");
+ try {
+ restoreField(hooked, "traceId", original.traceId);
+ restoreField(hooked, "spanId", original.spanId);
+ restoreField(hooked, "parentSpanId", original.parentSpanId);
+ restoreField(hooked, "traceState", original.traceState);
+ } catch {
+ return withRestoredIdentity(hooked, original);
+ }
+ return hooked;
+ }
+ _recordDrop(count, reason) {
+ this._droppedSinceWarning += count;
+ this._dropReasons.add(reason);
+ if (Date.now() - this._lastDropWarningAt >= this._config.flushIntervalMs)
+ this._warnAboutDrops();
+ }
+ _warnAboutDrops() {
+ if (!this._droppedSinceWarning)
return;
- const doShutdown = async () => {
+ this._lastDropWarningAt = Date.now();
+ this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[
+ ...this._dropReasons
+ ].join("; ")}`);
+ this._droppedSinceWarning = 0;
+ this._dropReasons.clear();
+ }
+ _encodeBatch(batch) {
+ const encoded = [];
+ for (const record of batch)
try {
- await this.promiseQueue.join();
- while (true) {
- const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
- if (!hasQueuedEvents)
- break;
- const dequeuedBeforeFlush = this._dequeuedMessagesCount;
- await this.flush();
- if (hasTimedOut)
- break;
- if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
- this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
- break;
+ encoded.push(buildOtlpSpan(record, this._logger));
+ } catch (error) {
+ this._logger.debug("Failed to encode a span; dropping it", error);
+ this._recordDrop(1, "its attributes could not be encoded");
+ }
+ return encoded;
+ }
+ _discardQueueIfConsentWithdrawn() {
+ if (!this._instance.isDisabled && !this._instance.optedOut)
+ return 0;
+ const discarded = this._queue.length;
+ this._queue = [];
+ this._resetHeadBatchBudget();
+ this._recordDrop(discarded, "the user has opted out");
+ this._warnAboutDrops();
+ return discarded;
+ }
+ async _flushInner() {
+ if (!this._queue.length)
+ return 0;
+ const discardedBeforeDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedBeforeDrain)
+ return discardedBeforeDrain;
+ const resourceAttributes = truncateAttributes(buildTracesResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._config.maxAttributeValueLength);
+ const scopeName = this._instance.getLibraryId();
+ const scopeVersion = this._instance.getLibraryVersion();
+ let remaining = this._queue.length;
+ let removed = 0;
+ let localCap = 1 / 0;
+ const generation = this._generation;
+ try {
+ while (remaining > 0 && this._queue.length > 0) {
+ const discardedMidDrain = this._discardQueueIfConsentWithdrawn();
+ if (discardedMidDrain)
+ return removed + discardedMidDrain;
+ const cap = this._headBatchFailures > 0 ? Math.min(this._maxExportBatchSize, this._headBatchSize) : this._maxExportBatchSize;
+ const size = Math.max(1, Math.min(cap, localCap, remaining, this._queue.length));
+ const batch = this._queue.slice(0, size);
+ const spans = this._encodeBatch(batch);
+ if (!spans.length) {
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._resetHeadBatchBudget();
+ continue;
+ }
+ const chargeable = clockNow() >= this._headBatchChargeableAt && !this._retryAfter.isOpen();
+ const outcome = await this._instance._sendTracesBatch(buildOtlpTracesPayload(spans, resourceAttributes, scopeName, scopeVersion, this._logger));
+ if (generation !== this._generation)
+ break;
+ this._retryAfter.record(outcome);
+ if (outcome.kind === "ok") {
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ if (this._maxExportBatchSize < this._config.maxExportBatchSize)
+ this._maxExportBatchSize++;
+ continue;
+ }
+ if (outcome.kind === "too-large") {
+ if (size === 1) {
+ this._queue.splice(0, 1);
+ remaining -= 1;
+ removed += 1;
+ this._recordDrop(1, "it is too large for the ingestion endpoint");
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ continue;
}
+ const halved = Math.max(1, Math.floor(size / 2));
+ if (outcome.measuredLocally)
+ localCap = halved;
+ else
+ this._maxExportBatchSize = halved;
+ this._resetHeadBatchBudget();
+ this._logger.debug(`Batch too large; retrying the same spans in batches of ${halved}`);
+ continue;
}
- } catch (e) {
- if (!isPostHogFetchError(e))
- throw e;
- await logFlushError(e);
+ if (outcome.kind === "retry-later") {
+ this._consecutiveFlushFailures++;
+ this._flushJitter = drawJitter();
+ this._headBatchSize = size;
+ if (chargeable) {
+ this._headBatchFailures++;
+ this._headBatchChargeableAt = clockNow() + this._nextFlushDelay();
+ }
+ if (this._headBatchFailures < MAX_RETRIES_PER_BATCH) {
+ this._logger.debug("Span export failed; retrying on the next flush", outcome.error);
+ return removed;
+ }
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, `the ingestion endpoint failed ${MAX_RETRIES_PER_BATCH} times in a row`);
+ if (this._retryAfter.isOpen())
+ return removed;
+ continue;
+ }
+ this._logger.debug("Dropping a span batch the ingestion endpoint rejected", outcome.error);
+ this._queue.splice(0, size);
+ remaining -= size;
+ removed += size;
+ this._consecutiveFlushFailures = 0;
+ this._flushJitter = NO_JITTER;
+ this._resetHeadBatchBudget();
+ this._recordDrop(size, "the ingestion endpoint rejected the batch");
}
- };
- return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
- this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
- shutdownTimeoutMs
- });
- hasTimedOut = true;
+ return removed;
+ } finally {
+ this._warnAboutDrops();
+ }
+ }
+ _flushInBackground() {
+ if (this._backgroundFlush)
+ return;
+ this._backgroundFlush = this.flush().catch((error) => {
+ this._logger.debug("Background span flush failed", error);
+ }).finally(() => {
+ this._backgroundFlush = undefined;
+ this._armFlushTimerIfQueuedNoEarlierThan();
});
}
- async shutdown(shutdownTimeoutMs = 30000) {
- if (this.shutdownPromise)
- this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
- else
- this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
- this.shutdownPromise = null;
- });
- return this.shutdownPromise;
+ _armFlushTimerIfQueued() {
+ if (this._flushTimer.pending || !this._queue.length)
+ return;
+ this._flushTimer.arm(this._nextFlushDelay());
+ }
+ _armFlushTimerIfQueuedNoEarlierThan() {
+ if (!this._queue.length)
+ return;
+ this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
+ }
+ _nextFlushDelay() {
+ return Math.max(backoffDelayMs(this._config.flushIntervalMs, this._consecutiveFlushFailures, this._flushJitter, MAX_FLUSH_BACKOFF_MS), this._retryAfter.remainingMs());
}
}
-var PostHogFetchHttpError, PostHogFetchNetworkError, applyCallerFeatureFlagOverrides = (target, callerProperties) => {
- for (const key of Object.keys(callerProperties))
- if (key.startsWith("$feature/") || key === "$active_feature_flags")
- target[key] = callerProperties[key];
-}, DEFAULT_QUEUE_ROUTE = "default";
-var init_posthog_core_stateless = __esm(() => {
- init_eventemitter();
- init_featureFlagUtils();
- init_gzip();
- init_types7();
+var MAX_RETRIES_PER_BATCH = 8;
+var init_traces = __esm(() => {
+ init_span();
+ init_ids();
+ init_traceparent();
+ init_sanitize();
+ init_json_utils();
+ init_otlp();
init_utils();
- init_uuidv7();
- init_error_tracking();
- PostHogFetchHttpError = class PostHogFetchHttpError extends Error {
- constructor(response, reqByteLength, responseBodyDeadline, abortController) {
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
- }
- get status() {
- return this.response.status;
- }
- get bodyReadTimedOut() {
- return this._bodyReadTimedOut;
- }
- get text() {
- if (!this.responseBodyTextPromise)
- if (Date.now() >= this.responseBodyDeadline) {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- this.cancelResponseBody(timeoutError);
- this.responseBodyTextPromise = Promise.reject(timeoutError);
- } else {
- const responseBodyTimeout = new Promise((_resolve, reject) => {
- this.responseBodyTimer = safeSetTimeout(() => {
- this._bodyReadTimedOut = true;
- const timeoutError = new Error("Response body read timed out");
- timeoutError.name = "AbortError";
- reject(timeoutError);
- this.cancelResponseBody(timeoutError);
- }, this.responseBodyDeadline - Date.now());
- });
- let responseBodyText;
- try {
- responseBodyText = Promise.resolve(this.response.text());
- } catch (error) {
- responseBodyText = Promise.reject(error);
- }
- this.responseBodyTextPromise = Promise.race([
- responseBodyText,
- responseBodyTimeout
- ]).finally(() => clearTimeout(this.responseBodyTimer));
- }
- return this.responseBodyTextPromise;
- }
- get json() {
- return this.text.then((text) => JSON.parse(text));
- }
- cancelResponseBody(reason) {
- clearTimeout(this.responseBodyTimer);
- if (!this.abortController.signal.aborted)
- this.abortController.abort(reason);
- (async () => {
- try {
- await this.response.body?.cancel();
- } catch {}
- })();
- }
- };
- PostHogFetchNetworkError = class PostHogFetchNetworkError extends Error {
- constructor(error) {
- super("Network error while fetching PostHog", error instanceof Error ? {
- cause: error
- } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
+ init_flush_timer();
+ init_retry_after();
+ init_backoff();
+});
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/context.mjs
+class SyncSpanContextManager {
+ active() {
+ return this._active;
+ }
+ with(span, fn) {
+ const previous = this._active;
+ this._active = span;
+ try {
+ return fn();
+ } finally {
+ this._active = previous;
}
+ }
+}
+var init_context = () => {};
+
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/traces/config.mjs
+function positiveInteger(value, fallback) {
+ return typeof value == "number" && Number.isInteger(value) && value >= 1 ? value : fallback;
+}
+function withUsableIdentityKeys(attributes) {
+ if (!attributes || typeof attributes != "object" || Array.isArray(attributes))
+ return;
+ try {
+ if (IDENTITY_KEYS.every((key) => !(key in attributes) || typeof attributes[key] == "string"))
+ return attributes;
+ const usable = {
+ ...attributes
+ };
+ for (const key of IDENTITY_KEYS)
+ if (key in usable && typeof usable[key] != "string")
+ delete usable[key];
+ return usable;
+ } catch {
+ return;
+ }
+}
+function resolveBeforeSpanSend(beforeSpanSend, logger) {
+ if (!beforeSpanSend)
+ return [];
+ const supplied = [
+ beforeSpanSend
+ ].flat().filter((hook) => Boolean(hook));
+ const hooks = supplied.filter((hook) => typeof hook == "function");
+ if (hooks.length !== supplied.length)
+ logger?.critical(`beforeSpanSend: ignoring ${supplied.length - hooks.length} of ${supplied.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);
+ return hooks;
+}
+function resolveTracesConfig(config, hostResourceAttributes, logger) {
+ const resourceAttributes = assignUserAttributes({
+ ...hostResourceAttributes
+ }, withUsableIdentityKeys(config?.resourceAttributes));
+ const maxExportBatchSize = positiveInteger(config?.maxExportBatchSize, DEFAULT_MAX_EXPORT_BATCH_SIZE);
+ return {
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
+ resourceAttributes,
+ beforeSpanSend: resolveBeforeSpanSend(config?.beforeSpanSend, logger),
+ maxAttributesPerSpan: positiveInteger(config?.maxAttributesPerSpan, DEFAULT_MAX_ATTRIBUTES_PER_SPAN),
+ maxEventsPerSpan: positiveInteger(config?.maxEventsPerSpan, DEFAULT_MAX_EVENTS_PER_SPAN),
+ maxAttributesPerEvent: DEFAULT_MAX_ATTRIBUTES_PER_EVENT,
+ maxAttributeValueLength: positiveInteger(config?.maxAttributeValueLength, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH),
+ flushIntervalMs: positiveInteger(config?.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS2),
+ maxExportBatchSize,
+ maxQueueSize: Math.max(positiveInteger(config?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE), maxExportBatchSize),
+ maxLiveSpans: positiveInteger(config?.maxLiveSpans, DEFAULT_MAX_LIVE_SPANS),
+ maxSpanAgeMs: positiveInteger(config?.maxSpanAgeMs, DEFAULT_MAX_SPAN_AGE_MS)
};
+}
+var DEFAULT_FLUSH_INTERVAL_MS2 = 5000, DEFAULT_MAX_EXPORT_BATCH_SIZE = 512, DEFAULT_MAX_QUEUE_SIZE = 2048, DEFAULT_MAX_ATTRIBUTES_PER_SPAN = 128, DEFAULT_MAX_EVENTS_PER_SPAN = 128, DEFAULT_MAX_ATTRIBUTES_PER_EVENT = 128, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 8192, DEFAULT_MAX_LIVE_SPANS = 1e4, DEFAULT_MAX_SPAN_AGE_MS = 3600000, IDENTITY_KEYS;
+var init_config3 = __esm(() => {
+ init_json_utils();
+ IDENTITY_KEYS = [
+ "service.name",
+ "service.version",
+ "deployment.environment"
+ ];
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/posthog-core.mjs
-var init_posthog_core = __esm(() => {
- init_featureFlagUtils();
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/surveys/validation.mjs
+var init_validation = __esm(() => {
init_types7();
- init_posthog_core_stateless();
- init_uuidv7();
- init_utils();
-});
-
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/tracing-headers.mjs
-var init_tracing_headers = __esm(() => {
- init_type_utils();
});
-// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@posthog/core/dist/index.mjs
var init_dist2 = __esm(() => {
+ init_error_tracking();
init_featureFlagUtils();
+ init_featureFlagLocalEvaluation();
init_gzip();
init_logs_utils();
+ init_otlp_any_value();
+ init_otlp_resource();
init_logs();
init_metrics();
+ init_traces();
+ init_context();
+ init_span();
+ init_config3();
init_uuidv7();
init_validation();
- init_error_tracking();
init_utils();
init_cookie();
init_posthog_core();
@@ -81000,7 +84685,7 @@ var init_dist2 = __esm(() => {
init_types7();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
import { constants as constants6 } from "fs";
import { open as promises_open } from "fs/promises";
import { isAbsolute as isAbsolute7 } from "path";
@@ -81287,7 +84972,7 @@ var init_context_lines_node = __esm(() => {
LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
import { isAbsolute as isAbsolute8, relative as relative4, sep as sep8 } from "path";
function createRelativePathModifier(basePath = process.cwd()) {
const isWindows = sep8 === "\\";
@@ -81304,11 +84989,11 @@ function createRelativePathModifier(basePath = process.cwd()) {
}
var init_relative_path_node = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
-var version2 = "5.51.1";
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/version.mjs
+var version2 = "5.52.4";
var init_version = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/types.mjs
var FeatureFlagError2;
var init_types9 = __esm(() => {
FeatureFlagError2 = {
@@ -81319,7 +85004,7 @@ var init_types9 = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
class FeatureFlagEvaluations {
constructor(init) {
this._host = init.host;
@@ -81455,18 +85140,7 @@ var init_feature_flag_evaluations = __esm(() => {
init_types9();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
-async function hashSHA1(text) {
- const subtle = globalThis.crypto?.subtle;
- if (!subtle)
- throw new Error("SubtleCrypto API not available");
- const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
-}
-var init_crypto = () => {};
-
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
function setCustomErrorPrototype(error, constructor) {
error.name = constructor.name;
Error.captureStackTrace(error, constructor);
@@ -81479,6 +85153,7 @@ class FeatureFlagsPoller {
this.shouldBeginExponentialBackoff = false;
this.backOffCount = 0;
this.pollerStopped = false;
+ this.filteredOutFlagKeys = new Set;
this.pollingInterval = pollingInterval;
this.personalApiKey = personalApiKey;
this.featureFlags = [];
@@ -81497,6 +85172,7 @@ class FeatureFlagsPoller {
this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
this.cacheProvider = options.cacheProvider;
this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
+ this.evaluationContexts = options.evaluationContexts;
this.loadFeatureFlags();
}
debug(enabled = true) {
@@ -81628,23 +85304,7 @@ class FeatureFlagsPoller {
return distinctId;
}
getFeatureFlagPayload(key, flagValue) {
- let payload = null;
- if (flagValue !== false && flagValue != null) {
- if (typeof flagValue == "boolean")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
- else if (typeof flagValue == "string")
- payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
- if (payload != null) {
- if (typeof payload == "object")
- return payload;
- if (typeof payload == "string")
- try {
- return JSON.parse(payload);
- } catch {}
- return payload;
- }
- }
- return null;
+ return resolveFeatureFlagPayload(this.featureFlagsByKey?.[key]?.filters?.payloads, flagValue);
}
async evaluateFlagDependency(property, properties, evaluationContext) {
const { evaluationCache } = evaluationContext;
@@ -81671,6 +85331,8 @@ class FeatureFlagsPoller {
}
else
evaluationCache[depFlagKey] = false;
+ else if (this.filteredOutFlagKeys.has(depFlagKey))
+ evaluationCache[depFlagKey] = false;
else
throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
}
@@ -81723,8 +85385,11 @@ class FeatureFlagsPoller {
result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
break;
}
- if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound") {
+ if (isInconclusive)
+ break;
return false;
+ }
} catch (e) {
if (e instanceof RequiresServerEvaluation)
throw e;
@@ -81759,36 +85424,33 @@ class FeatureFlagsPoller {
if (rolloutPercentage == undefined)
return "match";
}
- if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
+ if (rolloutPercentage != null && await getFeatureFlagHash(flag.key, bucketingValue) > rolloutPercentage / 100)
return "out_of_rollout_bound";
return "match";
}
async getMatchingVariant(flag, bucketingValue) {
- const hashValue = await _hash(flag.key, bucketingValue, "variant");
- const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
- if (matchingVariant)
- return matchingVariant.key;
+ return getFeatureFlagVariant(flag.key, bucketingValue, flag.filters?.multivariate?.variants || []);
}
variantLookupTable(flag) {
- const lookupTable = [];
- let valueMin = 0;
- let valueMax = 0;
- const flagFilters = flag.filters || {};
- const multivariates = flagFilters.multivariate?.variants || [];
- multivariates.forEach((variant) => {
- valueMax = valueMin + variant.rollout_percentage / 100;
- lookupTable.push({
- valueMin,
- valueMax,
- key: variant.key
- });
- valueMin = valueMax;
+ return getFeatureFlagVariantLookupTable(flag.filters?.multivariate?.variants || []);
+ }
+ filterFlagsByEvaluationContexts(flags) {
+ if (!this.evaluationContexts || this.evaluationContexts.length === 0)
+ return flags;
+ const contexts = new Set(this.evaluationContexts);
+ return flags.filter((flag) => {
+ const tags = flag.evaluation_contexts ?? flag.evaluation_tags;
+ if (!tags || tags.length === 0)
+ return true;
+ return tags.some((tag) => contexts.has(tag));
});
- return lookupTable;
}
updateFlagState(flagData) {
- this.featureFlags = flagData.flags;
- this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const flags = this.filterFlagsByEvaluationContexts(flagData.flags);
+ this.featureFlags = flags;
+ this.featureFlagsByKey = flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
+ const keptKeys = new Set(flags.map((flag) => flag.key));
+ this.filteredOutFlagKeys = new Set(flagData.flags.filter((flag) => !keptKeys.has(flag.key)).map((flag) => flag.key));
this.groupTypeMapping = flagData.groupTypeMapping;
this.cohorts = flagData.cohorts;
this.loadedSuccessfullyOnce = true;
@@ -81810,7 +85472,7 @@ class FeatureFlagsPoller {
this.updateFlagState(cached);
this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(cached.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
return true;
}
return false;
@@ -81888,6 +85550,7 @@ class FeatureFlagsPoller {
console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
this.featureFlags = [];
this.featureFlagsByKey = {};
+ this.filteredOutFlagKeys = new Set;
this.groupTypeMapping = {};
this.cohorts = {};
this.onMinimalFlagCalledEvents?.(false);
@@ -81919,7 +85582,7 @@ class FeatureFlagsPoller {
this.onError?.(new Error(`Failed to store in cache: ${err}`));
}
this.onLoad?.(this.featureFlags.length);
- this.warnAboutExperienceContinuityFlags(flagData.flags);
+ this.warnAboutExperienceContinuityFlags(this.featureFlags);
break;
}
default:
@@ -82005,136 +85668,10 @@ class FeatureFlagsPoller {
}
}
}
-async function _hash(key, bucketingValue, salt = "") {
- const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
- return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
-}
function matchProperty(property, propertyValues, warnFunction) {
- const key = property.key;
- const value = property.value;
- const operator = property.operator || "exact";
- if (key in propertyValues) {
- if (operator === "is_not_set")
- return false;
- } else {
- if (operator === "is_not_set")
- return true;
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
- }
- const overrideValue = propertyValues[key];
- if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
- if (warnFunction)
- warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
- return false;
- }
- function computeExactMatch(value, overrideValue) {
- if (Array.isArray(value))
- return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
- return String(value).toLowerCase() === String(overrideValue).toLowerCase();
- }
- function compare(lhs, rhs, operator) {
- if (operator === "gt")
- return lhs > rhs;
- if (operator === "gte")
- return lhs >= rhs;
- if (operator === "lt")
- return lhs < rhs;
- if (operator === "lte")
- return lhs <= rhs;
- throw new Error(`Invalid operator: ${operator}`);
- }
- switch (operator) {
- case "exact":
- return computeExactMatch(value, overrideValue);
- case "is_not":
- return !computeExactMatch(value, overrideValue);
- case "is_set":
- return key in propertyValues;
- case "icontains":
- return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "not_icontains":
- return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
- case "starts_with":
- return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "not_starts_with":
- return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
- case "ends_with":
- return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "not_ends_with":
- return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
- case "regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
- case "not_regex":
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
- case "gt":
- case "gte":
- case "lt":
- case "lte": {
- const parsedValue = typeof value == "number" ? value : parseFloat(String(value));
- let parsedOverride;
- parsedOverride = typeof overrideValue == "number" ? overrideValue : overrideValue != null ? parseFloat(String(overrideValue)) : NaN;
- if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride))
- return compare(parsedOverride, parsedValue, operator);
- return compare(String(overrideValue), String(value), operator);
- }
- case "is_date_after":
- case "is_date_before": {
- if (typeof value == "boolean")
- throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
- if (parsedDate == null)
- parsedDate = convertToDateTime(value);
- if (parsedDate == null)
- throw new InconclusiveMatchError(`Invalid date: ${value}`);
- const overrideDate = convertToDateTime(overrideValue);
- if ([
- "is_date_before"
- ].includes(operator))
- return overrideDate < parsedDate;
- return overrideDate > parsedDate;
- }
- case "semver_eq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp === 0;
- }
- case "semver_neq": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp !== 0;
- }
- case "semver_gt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp > 0;
- }
- case "semver_gte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp >= 0;
- }
- case "semver_lt": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp < 0;
- }
- case "semver_lte": {
- const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));
- return cmp <= 0;
- }
- case "semver_tilde": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeTildeBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_caret": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeCaretBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- case "semver_wildcard": {
- const overrideParsed = parseSemver(String(overrideValue));
- const { lower, upper } = computeWildcardBounds(String(value));
- return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;
- }
- default:
- throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
- }
+ return matchFeatureFlagProperty(property, propertyValues, {
+ warnFunction
+ });
}
function checkCohortExists(cohortId, cohortProperties) {
if (!(cohortId in cohortProperties))
@@ -82214,187 +85751,9 @@ async function matchPropertyGroup(propertyGroup, propertyValues, cohortPropertie
throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
return propertyGroupType === "AND";
}
-function isValidRegex(regex) {
- try {
- new RegExp(regex);
- return true;
- } catch (err) {
- return false;
- }
-}
-function parseSemverNumericIdentifier(part, raw) {
- if (!/^\d+$/.test(part))
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- if (part.length > 1 && part[0] === "0")
- throw new InconclusiveMatchError(`Invalid semver: ${raw}`);
- return parseInt(part, 10);
-}
-function parseSemver(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const baseVersion = text.split("-")[0].split("+")[0];
- if (!baseVersion || baseVersion.startsWith("."))
- throw new InconclusiveMatchError(`Invalid semver: ${value}`);
- const parts = baseVersion.split(".");
- const parsePart = (part) => {
- if (part === undefined || part === "")
- return 0;
- return parseSemverNumericIdentifier(part, value);
- };
- const major = parsePart(parts[0]);
- const minor = parsePart(parts[1]);
- const patch = parsePart(parts[2]);
- return [
- major,
- minor,
- patch
- ];
-}
-function compareSemverTuples(a, b) {
- for (let i = 0;i < 3; i++) {
- if (a[i] < b[i])
- return -1;
- if (a[i] > b[i])
- return 1;
- }
- return 0;
-}
-function computeTildeBounds(value) {
- const parsed = parseSemver(value);
- const lower = [
- parsed[0],
- parsed[1],
- parsed[2]
- ];
- const upper = [
- parsed[0],
- parsed[1] + 1,
- 0
- ];
- return {
- lower,
- upper
- };
-}
-function computeCaretBounds(value) {
- const parsed = parseSemver(value);
- const [major, minor, patch] = parsed;
- const lower = [
- major,
- minor,
- patch
- ];
- let upper;
- upper = major > 0 ? [
- major + 1,
- 0,
- 0
- ] : minor > 0 ? [
- 0,
- minor + 1,
- 0
- ] : [
- 0,
- 0,
- patch + 1
- ];
- return {
- lower,
- upper
- };
-}
-function computeWildcardBounds(value) {
- const text = String(value).trim().replace(/^[vV]/, "");
- const cleanedText = text.replace(/\.\*$/, "").replace(/\*$/, "");
- if (!cleanedText)
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- const parts = cleanedText.split(".");
- const parseWildcardPart = (part) => {
- try {
- return parseSemverNumericIdentifier(part, value);
- } catch {
- throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);
- }
- };
- const major = parseWildcardPart(parts[0]);
- let lower;
- let upper;
- if (parts.length === 1) {
- lower = [
- major,
- 0,
- 0
- ];
- upper = [
- major + 1,
- 0,
- 0
- ];
- } else {
- const minor = parseWildcardPart(parts[1]);
- lower = [
- major,
- minor,
- 0
- ];
- upper = [
- major,
- minor + 1,
- 0
- ];
- }
- return {
- lower,
- upper
- };
-}
-function convertToDateTime(value) {
- if (value instanceof Date)
- return value;
- if (typeof value == "string" || typeof value == "number") {
- const date = new Date(value);
- if (!isNaN(date.valueOf()))
- return date;
- throw new InconclusiveMatchError(`${value} is in an invalid date format`);
- }
- throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
-}
-function relativeDateParseForFeatureFlagMatching(value) {
- const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
- const match = value.match(regex);
- const parsedDt = new Date(new Date().toISOString());
- if (!match)
- return null;
- {
- if (!match.groups)
- return null;
- const number = parseInt(match.groups["number"]);
- if (number >= 1e4)
- return null;
- const interval = match.groups["interval"];
- if (interval == "h")
- parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
- else if (interval == "d")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
- else if (interval == "w")
- parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
- else if (interval == "m")
- parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
- else {
- if (interval != "y")
- return null;
- parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
- }
- return parsedDt;
- }
-}
-var SIXTY_SECONDS = 60000, LONG_SCALE = 1152921504606847000, NULL_VALUES_ALLOWED_OPERATORS, ClientError, InconclusiveMatchError, RequiresServerEvaluation;
+var SIXTY_SECONDS = 60000, ClientError, RequiresServerEvaluation;
var init_feature_flags = __esm(() => {
init_dist2();
- init_crypto();
- NULL_VALUES_ALLOWED_OPERATORS = [
- "is_not",
- "is_set"
- ];
ClientError = class ClientError extends Error {
constructor(message) {
super();
@@ -82404,12 +85763,6 @@ var init_feature_flags = __esm(() => {
Object.setPrototypeOf(this, ClientError.prototype);
}
};
- InconclusiveMatchError = class InconclusiveMatchError extends Error {
- constructor(message) {
- super(message);
- setCustomErrorPrototype(this, InconclusiveMatchError);
- }
- };
RequiresServerEvaluation = class RequiresServerEvaluation extends Error {
constructor(message) {
super(message);
@@ -82418,7 +85771,7 @@ var init_feature_flags = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
function splitNodeOptions(nodeOptions) {
const args = [];
let current = "";
@@ -82519,7 +85872,7 @@ var init_autocapture = __esm(() => {
STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
class error_tracking_ErrorTracking {
constructor(client, options, _logger) {
this.client = client;
@@ -82587,13 +85940,14 @@ class error_tracking_ErrorTracking {
this._rateLimiter.stop();
}
}
-var SHUTDOWN_TIMEOUT = 2000;
+var SHUTDOWN_TIMEOUT = 2000, error_tracking_default;
var init_error_tracking2 = __esm(() => {
init_autocapture();
init_dist2();
+ error_tracking_default = error_tracking_ErrorTracking;
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/storage-memory.mjs
class PostHogMemoryStorage {
getProperty(key) {
return this._memoryStorage[key];
@@ -82607,24 +85961,24 @@ class PostHogMemoryStorage {
}
var init_storage_memory = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/config.mjs
function isCaptureMode(value) {
return value === "v0" || value === "v1";
}
function resolveCaptureMode() {
- const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
+ const envMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
return isCaptureMode(envMode) ? envMode : "v0";
}
-var init_config3 = () => {};
+var init_config4 = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/routing.mjs
function isLegacyOnlyEvent(message) {
return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
}
var AI_EVENT_PREFIX = "$ai_", ANALYTICS_ROUTE = "analytics", AI_ROUTE = "ai";
var init_routing = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/errors.mjs
var CaptureV1Error;
var init_errors3 = __esm(() => {
CaptureV1Error = class CaptureV1Error extends Error {
@@ -82644,7 +85998,7 @@ var init_errors3 = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/transform.mjs
function coerceBool(value) {
if (typeof value == "boolean")
return value;
@@ -82762,7 +86116,7 @@ var init_transform = __esm(() => {
];
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/capture-v1/sender.mjs
class V1CaptureSender {
constructor(config, hooks) {
this.config = config;
@@ -83018,11 +86372,11 @@ var init_sender = __esm(() => {
]);
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/routing.mjs
var AI_CAPTURE_ROUTE = "ai-capture", AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/", AI_MAX_EVENT_BYTES = 8388608, AI_BATCH_TARGET_BYTES = 5242880;
var init_routing2 = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/ai-capture/batching.mjs
function eventByteSize(message) {
return encoder.encode(safeJsonStringify(message)).length;
}
@@ -83064,7 +86418,7 @@ var init_batching = __esm(() => {
encoder = new TextEncoder;
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/client.mjs
function emitDeprecationWarningOnce(id, message) {
if (_emittedDeprecations.has(id))
return;
@@ -83108,7 +86462,7 @@ var init_client3 = __esm(() => {
init_feature_flags();
init_error_tracking2();
init_storage_memory();
- init_config3();
+ init_config4();
init_routing();
init_sender();
init_batching();
@@ -83157,10 +86511,11 @@ var init_client3 = __esm(() => {
},
customHeaders: this.getCustomHeaders(),
cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
- strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
+ strictLocalEvaluation: normalizedOptions.strictLocalEvaluation,
+ evaluationContexts: normalizedOptions.evaluationContexts ?? normalizedOptions.evaluationEnvironments
});
}
- this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
+ this.errorTracking = new error_tracking_default(this, normalizedOptions, this._logger);
this.distinctIdHasSentFlagCalls = {};
this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
}
@@ -83168,8 +86523,26 @@ var init_client3 = __esm(() => {
super.enqueue(type, message, options, explicitRoute);
this.scheduleDebouncedFlush();
}
+ _flushEventsAndSpans(skipThrottledSpans = false) {
+ const events = this.flushWithPendingPromises();
+ if (!this._traces || skipThrottledSpans && this._traces.throttled)
+ return events;
+ return allSettled([
+ events,
+ this._traces.flush().catch(() => {})
+ ]).then(([eventsResult]) => {
+ if (eventsResult.status === "rejected")
+ throw eventsResult.reason;
+ });
+ }
+ flushAutomatic() {
+ return this._flushKeepingRuntimeAlive(true);
+ }
async flush() {
- const flushPromise = this.flushWithPendingPromises();
+ return this._flushKeepingRuntimeAlive(false);
+ }
+ _flushKeepingRuntimeAlive(skipThrottledSpans) {
+ const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
const waitUntil = this.options.waitUntil;
if (waitUntil && !this._waitUntilCycle)
try {
@@ -83222,7 +86595,7 @@ var init_client3 = __esm(() => {
async resolveWaitUntilFlush() {
const resolve = this._consumeWaitUntilCycle();
try {
- await this.flushWithPendingPromises();
+ await this._flushEventsAndSpans();
} catch {} finally {
resolve?.();
}
@@ -83324,9 +86697,51 @@ var init_client3 = __esm(() => {
this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
return this._metrics;
}
+ initializeSpanContextManager() {
+ return new SyncSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return {};
+ }
+ get _spanContextManager() {
+ if (!this._spanContext)
+ this._spanContext = this.initializeSpanContextManager();
+ return this._spanContext;
+ }
+ get _tracesPipeline() {
+ if (!this.options.traces)
+ return;
+ if (!this._traces)
+ this._traces = new PostHogTraces(this, resolveTracesConfig(this.options.traces, this.hostResourceAttributes(), this._logger), this._logger, () => this._tracingContext(), this._spanContextManager, () => this.scheduleDebouncedFlush());
+ return this._traces;
+ }
+ _tracingContext() {
+ const context = this.context?.get();
+ return {
+ distinctId: context?.distinctId,
+ sessionId: context?.sessionId
+ };
+ }
+ startSpan(name, options) {
+ return this._tracesPipeline?.startSpan(name, options) ?? inertSpan(options, this._spanContextManager.active());
+ }
+ withSpan(name, optionsOrFn, maybeFn) {
+ const options = typeof optionsOrFn == "function" ? undefined : optionsOrFn;
+ const fn = typeof optionsOrFn == "function" ? optionsOrFn : maybeFn;
+ const pipeline = this._tracesPipeline;
+ if (!pipeline)
+ return runWithActiveSpan(this._spanContextManager, inertSpan(options, this._spanContextManager.active()), fn);
+ return options ? pipeline.withSpan(name, options, fn) : pipeline.withSpan(name, fn);
+ }
+ getActiveSpan() {
+ return this._spanContextManager.active() ?? null;
+ }
getCustomUserAgent() {
return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
}
+ getEvaluationRuntime() {
+ return "server";
+ }
getCommonEventProperties() {
const commonProperties = super.getCommonEventProperties();
if (this.options.isServer ?? true)
@@ -83814,7 +87229,16 @@ var init_client3 = __esm(() => {
flags: {}
});
}
- const { groups, disableGeoip, flagKeys } = resolvedOptions || {};
+ const { groups, disableGeoip } = resolvedOptions || {};
+ const flagKeys = resolvedOptions?.flagKeys ?? undefined;
+ if (flagKeys?.length === 0)
+ return new FeatureFlagEvaluations({
+ host: this._getFeatureFlagEvaluationsHost(),
+ distinctId: resolvedDistinctId,
+ groups,
+ disableGeoip,
+ flags: {}
+ });
let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};
const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
personProperties = adjustedProperties.allPersonProperties;
@@ -84068,6 +87492,10 @@ var init_client3 = __esm(() => {
await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
this._metrics.reset();
}
+ if (this._traces) {
+ await raceWithTimeout(this._traces.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
+ this._traces.reset();
+ }
try {
return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
} finally {
@@ -84196,9 +87624,9 @@ var init_client3 = __esm(() => {
};
}
captureException(error, distinctId, additionalProperties, uuid, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
...msg,
@@ -84208,9 +87636,9 @@ var init_client3 = __esm(() => {
}
}
async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
- if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
+ if (!error_tracking_default.isPreviouslyCapturedError(error)) {
const syntheticException = new Error("PostHog syntheticException");
- return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
+ return this.addPendingPromise(error_tracking_default.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
syntheticException
}, distinctId, additionalProperties).then((msg) => this.captureImmediate({
...msg,
@@ -84321,7 +87749,7 @@ var init_client3 = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/context.mjs
import { AsyncLocalStorage } from "async_hooks";
class PostHogContext {
@@ -84351,9 +87779,25 @@ class PostHogContext {
};
}
}
-var init_context = () => {};
+var init_context2 = () => {};
+
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/context/span-context.node.mjs
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
+
+class AsyncLocalStorageSpanContextManager {
+ active() {
+ return this._storage.getStore();
+ }
+ with(span, fn) {
+ return this._storage.run(span, fn);
+ }
+ constructor() {
+ this._storage = new AsyncLocalStorage2;
+ }
+}
+var init_span_context_node = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/gzip.node.mjs
import { gzip } from "zlib";
import { promisify } from "util";
async function gzipCompress2(input, isDebug = true) {
@@ -84371,7 +87815,22 @@ var init_gzip_node = __esm(() => {
gzipAsync = promisify(gzip);
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/host-os.node.mjs
+import { platform, release as release2 } from "os";
+function hostOsResourceAttributes() {
+ let osName;
+ let osVersion;
+ try {
+ osName = platform();
+ osVersion = release2();
+ } catch {}
+ return osResourceAttributes(osName, osVersion);
+}
+var init_host_os_node = __esm(() => {
+ init_dist2();
+});
+
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
"error"
], sendExceptionsToPostHog = true } = {}) {
@@ -84428,7 +87887,9 @@ var NAME = "posthog-node", PostHogSentryIntegration;
var init_sentry_integration = __esm(() => {
init_dist2();
PostHogSentryIntegration = class PostHogSentryIntegration {
- static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ static {
+ this.POSTHOG_ID_TAG = "posthog_distinct_id";
+ }
constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
this.name = NAME;
this.name = NAME;
@@ -84446,22 +87907,22 @@ var init_sentry_integration = __esm(() => {
};
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
var init_tracing_headers2 = () => {};
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/url-utils.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/url-utils.mjs
var init_url_utils = __esm(() => {
init_dist2();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/express.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/express.mjs
var init_express = __esm(() => {
init_error_tracking2();
init_tracing_headers2();
init_url_utils();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/exports.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/exports.mjs
var init_exports = __esm(() => {
init_feature_flag_evaluations();
init_dist2();
@@ -84470,7 +87931,7 @@ var init_exports = __esm(() => {
init_types9();
});
-// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
+// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/entrypoints/index.node.mjs
var PostHog;
var init_index_node = __esm(() => {
init_module_node();
@@ -84478,8 +87939,10 @@ var init_index_node = __esm(() => {
init_relative_path_node();
init_client3();
init_dist2();
- init_context();
+ init_context2();
+ init_span_context_node();
init_gzip_node();
+ init_host_os_node();
init_exports();
PostHog = class PostHog extends PostHogBackendClient {
getLibraryId() {
@@ -84491,6 +87954,12 @@ var init_index_node = __esm(() => {
initializeContext() {
return new PostHogContext;
}
+ initializeSpanContextManager() {
+ return new AsyncLocalStorageSpanContextManager;
+ }
+ hostResourceAttributes() {
+ return hostOsResourceAttributes();
+ }
createErrorPropertiesBuilder() {
return new ErrorPropertiesBuilder([
new EventCoercer,
@@ -84713,7 +88182,7 @@ var package_default2;
var init_package2 = __esm(() => {
package_default2 = {
name: "@oh-my-opencode/omo-codex",
- version: "5.0.0-beta.80",
+ version: "5.0.0-beta.81",
type: "module",
private: true,
description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -94476,7 +97945,7 @@ function isYes(value) {
return normalized === "y" || normalized === "yes";
}
-// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
import { stdout, stdin } from "process";
import * as l from "readline";
import l__default from "readline";
@@ -94822,7 +98291,7 @@ function wrapAnsi(string, columns, options) {
`);
}
-// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@clack/core/dist/index.mjs
var import_sisteransi = __toESM(require_src(), 1);
import { ReadStream } from "tty";
function findCursor(s, o, l) {
@@ -94861,6 +98330,7 @@ var settings = {
error: "Something went wrong"
},
withGuide: true,
+ accessible: undefined,
date: {
monthNames: [...t],
messages: {
@@ -94872,6 +98342,14 @@ var settings = {
}
}
};
+function isAccessible(n) {
+ if (n !== undefined)
+ return n;
+ if (settings.accessible !== undefined)
+ return settings.accessible;
+ const e = process.env.ACCESSIBLE;
+ return e !== undefined && e !== "" && e !== "0" && e !== "false";
+}
function isActionKey(n, e) {
if (typeof n == "string")
return settings.aliases.get(n) === e;
@@ -94908,7 +98386,7 @@ function block({
input: e = stdin,
output: r = stdout,
overwrite: o = true,
- hideCursor: t = true
+ hideCursor: n = true
} = {}) {
const s = l.createInterface({
input: e,
@@ -94917,10 +98395,10 @@ function block({
tabSize: 1
});
l.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
- const n = (f, { name: a, sequence: p }) => {
+ const t = (f, { name: a, sequence: w }) => {
const c = String(f);
- if (isActionKey([c, a, p], "cancel")) {
- t && r.write(import_sisteransi.cursor.show), process.exit(0);
+ if (isActionKey([c, a, w], "cancel")) {
+ n && r.write(import_sisteransi.cursor.show), process.exit(0);
return;
}
if (!o)
@@ -94928,39 +98406,37 @@ function block({
const i = a === "return" ? 0 : -1, m = a === "return" ? -1 : 0;
l.moveCursor(r, i, m, () => {
l.clearLine(r, 1, () => {
- e.once("keypress", n);
+ e.once("keypress", t);
});
});
};
- return t && r.write(import_sisteransi.cursor.hide), e.once("keypress", n), () => {
- e.off("keypress", n), t && r.write(import_sisteransi.cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
+ return n && r.write(import_sisteransi.cursor.hide), e.once("keypress", t), () => {
+ e.off("keypress", t), n && r.write(import_sisteransi.cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
};
}
var getColumns = (e) => ("columns" in e) && typeof e.columns == "number" ? e.columns : 80;
var getRows = (e) => ("rows" in e) && typeof e.rows == "number" ? e.rows : 20;
-function wrapTextWithPrefix(e, r, o, t = o, s = o, n) {
+function wrapTextWithPrefix(e, r, o, n = o, s = o, t) {
const f = getColumns(e ?? stdout);
return wrapAnsi(r, f - o.length, {
hard: true,
trim: false
}).split(`
`).map((c, i, m) => {
- const d = n ? n(c, i) : c;
- return i === 0 ? `${t}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;
+ const d = t ? t(c, i) : c;
+ return i === 0 ? `${n}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;
}).join(`
`);
}
-function runValidation(e, n) {
+function runValidation(e, a) {
if ("~standard" in e) {
- const a = e["~standard"].validate(n);
- if (a instanceof Promise)
- throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");
- return a.issues?.at(0)?.message;
+ const n = e["~standard"].validate(a);
+ return n instanceof Promise ? n.then((r) => r.issues?.at(0)?.message) : n.issues?.at(0)?.message;
}
- return e(n);
+ return e(a);
}
-class V {
+class y {
input;
output;
_abortSignal;
@@ -94975,9 +98451,12 @@ class V {
error = "";
value;
userInput = "";
+ get accessible() {
+ return isAccessible(this.opts.accessible);
+ }
constructor(t, e = true) {
- const { input: i = stdin, output: n = stdout, render: s, signal: r, ...o } = t;
- this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = s.bind(this), this._track = e, this._abortSignal = r, this.input = i, this.output = n;
+ const { input: i = stdin, output: s = stdout, render: r, signal: n, ...o } = t;
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r.bind(this), this._track = e, this._abortSignal = n, this.input = i, this.output = s;
}
unsubscribe() {
this._subscribers.clear();
@@ -94993,11 +98472,11 @@ class V {
this.setSubscriber(t, { cb: e, once: true });
}
emit(t, ...e) {
- const i = this._subscribers.get(t) ?? [], n = [];
- for (const s of i)
- s.cb(...e), s.once && n.push(() => i.splice(i.indexOf(s), 1));
- for (const s of n)
- s();
+ const i = this._subscribers.get(t) ?? [], s = [];
+ for (const r of i)
+ r.cb(...e), r.once && s.push(() => i.splice(i.indexOf(r), 1));
+ for (const r of s)
+ r();
}
prompt() {
return new Promise((t) => {
@@ -95036,15 +98515,18 @@ class V {
_clearUserInput() {
this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
}
- onKeypress(t, e) {
- if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
- if (this.opts.validate) {
- const i = runValidation(this.opts.validate, this.value);
- i && (this.error = i instanceof Error ? i.message : i, this.state = "error", this.rl?.write(this.userInput));
+ async onKeypress(t, e) {
+ if (this.state !== "validating") {
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
+ if (this.opts.validate) {
+ const i = runValidation(this.opts.validate, this.value);
+ let s;
+ i instanceof Promise ? (this.state = "validating", this.render(), s = await i) : s = i, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
+ }
+ this.state !== "error" && (this.state = "submit");
}
- this.state !== "error" && (this.state = "submit");
+ isActionKey([t, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
}
- isActionKey([t, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
}
close() {
this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
@@ -95066,28 +98548,28 @@ class V {
else {
const e = diffLines(this._prevFrame, t), i = getRows(this.output);
if (this.restoreCursor(), e) {
- const n = Math.max(0, e.numLinesAfter - i), s = Math.max(0, e.numLinesBefore - i);
- let r = e.lines.find((o) => o >= n);
- if (r === undefined) {
+ const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);
+ let n = e.lines.find((o) => o >= s);
+ if (n === undefined) {
this._prevFrame = t;
return;
}
if (e.lines.length === 1) {
- this.output.write(import_sisteransi.cursor.move(0, r - s)), this.output.write(import_sisteransi.erase.lines(1));
+ this.output.write(import_sisteransi.cursor.move(0, n - r)), this.output.write(import_sisteransi.erase.lines(1));
const o = t.split(`
`);
- this.output.write(o[r]), this._prevFrame = t, this.output.write(import_sisteransi.cursor.move(0, o.length - r - 1));
+ this.output.write(o[n]), this._prevFrame = t, this.output.write(import_sisteransi.cursor.move(0, o.length - n - 1));
return;
} else if (e.lines.length > 1) {
- if (n < s)
- r = n;
+ if (s < r)
+ n = s;
else {
- const h = r - s;
+ const h = n - r;
h > 0 && this.output.write(import_sisteransi.cursor.move(0, h));
}
this.output.write(import_sisteransi.erase.down());
const f = t.split(`
-`).slice(r);
+`).slice(n);
this.output.write(f.join(`
`)), this._prevFrame = t;
return;
@@ -95099,7 +98581,7 @@ class V {
}
}
}
-class r extends V {
+class r extends y {
get cursor() {
return this.value ? 0 : 1;
}
@@ -95116,7 +98598,7 @@ class r extends V {
});
}
}
-var n$1 = class n extends V {
+var n$1 = class n extends y {
options;
cursor = 0;
get _selectedValue() {
@@ -95145,7 +98627,7 @@ var n$1 = class n extends V {
}
};
-// node_modules/.bun/@[email protected]/node_modules/@clack/prompts/dist/index.mjs
+// node_modules/.bun/@[email protected]/node_modules/@clack/prompts/dist/index.mjs
import { styleText, stripVTControlCharacters as stripVTControlCharacters3 } from "util";
import process$1 from "process";
var import_sisteransi2 = __toESM(require_src(), 1);
@@ -95194,6 +98676,8 @@ var symbol = (o) => {
return styleText("yellow", S_STEP_ERROR);
case "submit":
return styleText("green", S_STEP_SUBMIT);
+ case "validating":
+ return styleText("dim", S_STEP_ACTIVE);
}
};
var symbolBar = (o) => {
@@ -95268,34 +98752,34 @@ var limitOptions = ({
x.push(n);
return c && x.push(M), x;
};
-var confirm = (i) => {
- const a = i.active ?? "Yes", s = i.inactive ?? "No";
+var confirm = (e) => {
+ const a = e.active ?? "Yes", o = e.inactive ?? "No";
return new r({
active: a,
- inactive: s,
- signal: i.signal,
- input: i.input,
- output: i.output,
- initialValue: i.initialValue ?? true,
+ inactive: o,
+ signal: e.signal,
+ input: e.input,
+ output: e.output,
+ initialValue: e.initialValue ?? true,
render() {
- const e = i.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = e ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(i.output, i.message, l, u), o = `${e ? `${styleText("gray", S_BAR)}
+ const i = e.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = i ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(e.output, e.message, l, u), s = `${i ? `${styleText("gray", S_BAR)}
` : ""}${f}
-`, c = this.value ? a : s;
+`, c = this.value ? a : o;
switch (this.state) {
case "submit": {
- const r = e ? `${styleText("gray", S_BAR)} ` : "";
- return `${o}${r}${styleText("dim", c)}`;
+ const r = i ? `${styleText("gray", S_BAR)} ` : "";
+ return `${s}${r}${styleText("dim", c)}`;
}
case "cancel": {
- const r = e ? `${styleText("gray", S_BAR)} ` : "";
- return `${o}${r}${styleText(["strikethrough", "dim"], c)}${e ? `
+ const r = i ? `${styleText("gray", S_BAR)} ` : "";
+ return `${s}${r}${styleText(["strikethrough", "dim"], c)}${i ? `
${styleText("gray", S_BAR)}` : ""}`;
}
default: {
- const r = e ? `${styleText("cyan", S_BAR)} ` : "", g = e ? styleText("cyan", S_BAR_END) : "";
- return `${o}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${i.vertical ? e ? `
+ const r = i ? `${styleText("cyan", S_BAR)} ` : "", g = i ? styleText("cyan", S_BAR_END) : "";
+ return `${s}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${e.vertical ? i ? `
${styleText("cyan", S_BAR)} ` : `
-` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", s)}` : `${styleText("green", S_RADIO_ACTIVE)} ${s}`}
+` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", o)}` : `${styleText("green", S_RADIO_ACTIVE)} ${o}`}
${g}
`;
}
@@ -95525,19 +99009,19 @@ ${styleText("gray", S_BAR)}` : ""}`;
}
default: {
const r = n ? `${styleText("cyan", S_BAR)} ` : "", a = u.split(`
-`).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n) : n ? [styleText("cyan", S_BAR_END)] : [], b = p.join(`
-`), f = p.length + 1;
+`).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n) : n ? [styleText("cyan", S_BAR_END)] : [], f = p.join(`
+`), b = p.length + 1;
return `${u}${r}${limitOptions({
output: t.output,
cursor: this.cursor,
options: this.options,
maxItems: t.maxItems,
columnPadding: r.length,
- rowPadding: a + f,
+ rowPadding: a + b,
style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
}).join(`
${r}`)}
-${b}
+${f}
`;
}
}
@@ -101941,7 +105425,7 @@ var package_default3 = {
typecheck: "tsgo --noEmit -p tsconfig.json"
},
dependencies: {
- "@clack/prompts": "^1.7.0",
+ "@clack/prompts": "^1.8.1",
"@modelcontextprotocol/sdk": "^1.30.0",
"@oh-my-opencode/agents-md-core": "workspace:*",
"@oh-my-opencode/boulder-state": "workspace:*",
@@ -101962,13 +105446,13 @@ var package_default3 = {
"@oh-my-opencode/tmux-core": "workspace:*",
"@oh-my-opencode/team-core": "workspace:*",
"@oh-my-opencode/utils": "workspace:*",
- "@opencode-ai/plugin": "1.18.22",
- "@opencode-ai/sdk": "1.18.22",
+ "@opencode-ai/plugin": "1.18.31",
+ "@opencode-ai/sdk": "1.18.31",
commander: "^15.0.0",
"jsonc-parser": "^3.3.1",
picocolors: "^1.1.1",
picomatch: "^4.0.7",
- zod: "^4.4.3"
+ zod: "^4.6.5"
}
};
diff --git a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json
index 968ba196..c8202fb8 100644
--- a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json
+++ b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Resetting Git Bash MCP Reminder",
+ "statusMessage": "(OmO 5.0.0-beta.81) Resetting Git Bash MCP Reminder",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook post-compact"
}
],
diff --git a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json
index 9c1bf84b..d609973a 100644
--- a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json
+++ b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Resetting LSP Diagnostics Cache",
+ "statusMessage": "(OmO 5.0.0-beta.81) Resetting LSP Diagnostics Cache",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-compact"
}
],
diff --git a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json
index 05d6d01c..4b4fcf42 100644
--- a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json
+++ b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Resetting Project Rule Cache",
+ "statusMessage": "(OmO 5.0.0-beta.81) Resetting Project Rule Cache",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-compact"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-comments.json b/plugins/omo/hooks/post-tool-use-checking-comments.json
index 890d4dff..cf58a9f3 100644
--- a/plugins/omo/hooks/post-tool-use-checking-comments.json
+++ b/plugins/omo/hooks/post-tool-use-checking-comments.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use",
"timeout": 30,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Comments",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Comments",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\comment-checker\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json
index 33d470aa..7880f2e4 100644
--- a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json
+++ b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use",
"timeout": 60,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking LSP Diagnostics",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking LSP Diagnostics",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json
index 485d860b..8212ff11 100644
--- a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json
+++ b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/teammode/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Thread Title Hygiene",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Thread Title Hygiene",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\teammode\\dist\\cli.js\" hook post-tool-use"
}
]
diff --git a/plugins/omo/hooks/post-tool-use-matching-project-rules.json b/plugins/omo/hooks/post-tool-use-matching-project-rules.json
index 0c89fc10..931b4cd2 100644
--- a/plugins/omo/hooks/post-tool-use-matching-project-rules.json
+++ b/plugins/omo/hooks/post-tool-use-matching-project-rules.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Matching Project Rules",
+ "statusMessage": "(OmO 5.0.0-beta.81) Matching Project Rules",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json
index d36acc00..ce047bae 100644
--- a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json
+++ b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook post-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Recording Spawn Admission",
+ "statusMessage": "(OmO 5.0.0-beta.81) Recording Spawn Admission",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook post-tool-use-spawn"
}
]
diff --git a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json
index 669e7d83..e882480d 100644
--- a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json
+++ b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Enforcing Unlimited Goal Budget",
+ "statusMessage": "(OmO 5.0.0-beta.81) Enforcing Unlimited Goal Budget",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use"
}
],
diff --git a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json
index 8e0a7812..887760b4 100644
--- a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json
+++ b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Guarding Ulw-Loop Spawns",
+ "statusMessage": "(OmO 5.0.0-beta.81) Guarding Ulw-Loop Spawns",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use-spawn"
}
]
diff --git a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json
index fa45f5f9..3750d1fc 100644
--- a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json
+++ b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Recommending Git Bash MCP",
+ "statusMessage": "(OmO 5.0.0-beta.81) Recommending Git Bash MCP",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook pre-tool-use"
}
],
diff --git a/plugins/omo/hooks/session-start-checking-auto-update.json b/plugins/omo/hooks/session-start-checking-auto-update.json
index cd2e4ee3..e7b68f50 100644
--- a/plugins/omo/hooks/session-start-checking-auto-update.json
+++ b/plugins/omo/hooks/session-start-checking-auto-update.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start",
"timeout": 15,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Auto Update",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Auto Update",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\scripts\\auto-update.mjs\" hook session-start"
}
],
diff --git a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json
index 5a161258..ea141c3e 100644
--- a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json
+++ b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json
@@ -8,7 +8,7 @@
"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"",
"timeout": 30,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Bootstrap Provisioning"
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Bootstrap Provisioning"
}
]
}
diff --git a/plugins/omo/hooks/session-start-loading-project-rules.json b/plugins/omo/hooks/session-start-loading-project-rules.json
index abf09dfb..516e229e 100644
--- a/plugins/omo/hooks/session-start-loading-project-rules.json
+++ b/plugins/omo/hooks/session-start-loading-project-rules.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Loading Project Rules",
+ "statusMessage": "(OmO 5.0.0-beta.81) Loading Project Rules",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook session-start"
}
]
diff --git a/plugins/omo/hooks/session-start-recording-session-telemetry.json b/plugins/omo/hooks/session-start-recording-session-telemetry.json
index 6e5479e8..4d6abca2 100644
--- a/plugins/omo/hooks/session-start-recording-session-telemetry.json
+++ b/plugins/omo/hooks/session-start-recording-session-telemetry.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start",
"timeout": 15,
- "statusMessage": "(OmO 5.0.0-beta.80) Recording Session Telemetry",
+ "statusMessage": "(OmO 5.0.0-beta.81) Recording Session Telemetry",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\telemetry\\dist\\cli.js\" hook session-start"
}
]
diff --git a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json
index 729cc57e..9fa24fba 100644
--- a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json
+++ b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ulw-Execute Continuation",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ulw-Execute Continuation",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-execute-continuation\\dist\\cli.js\" hook stop"
}
]
diff --git a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json
index f5e5408f..23519c4b 100644
--- a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json
+++ b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ulw-Loop Resume",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ulw-Loop Resume",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook stop"
}
]
diff --git a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
index 02779cef..bf51c9f5 100644
--- a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
+++ b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Verifying LazyCodex Executor Evidence",
+ "statusMessage": "(OmO 5.0.0-beta.81) Verifying LazyCodex Executor Evidence",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lazycodex-executor-verify\\dist\\cli.js\" hook subagent-stop"
}
],
diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json
index 5607cb8f..20a27ce2 100644
--- a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json
+++ b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ultrawork Trigger",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ultrawork Trigger",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ultrawork\\dist\\cli.js\" hook user-prompt-submit"
}
]
diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json
index c84feb78..97496ff5 100644
--- a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json
+++ b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Checking Ulw-Loop Steering",
+ "statusMessage": "(OmO 5.0.0-beta.81) Checking Ulw-Loop Steering",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook user-prompt-submit"
}
]
diff --git a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json
index e65a2ded..d4f7826b 100644
--- a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json
+++ b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.80) Loading Project Rules",
+ "statusMessage": "(OmO 5.0.0-beta.81) Loading Project Rules",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook user-prompt-submit"
}
]
diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.json
index 161c7be5..bf37a226 100644
--- a/plugins/omo/package-lock.json
+++ b/plugins/omo/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"workspaces": [
"components/comment-checker",
"components/git-bash",
@@ -21,6 +21,10 @@
],
"dependencies": {
"@oh-my-opencode/shared-skills": "file:../../shared-skills"
+ },
+ "devDependencies": {
+ "@vitest/coverage-v8": "5.0.1",
+ "vitest": "5.0.1"
}
},
"../../comment-checker-core": {
@@ -46,12 +50,13 @@
"omo-lsp-daemon": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.4.16",
+ "@biomejs/biome": "2.5.14",
"@oh-my-opencode/lsp-core": "file:../lsp-core",
"@oh-my-opencode/mcp-stdio-core": "file:../mcp-stdio-core",
- "@types/node": "^25.9.2",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^6.0.3",
- "vitest": "^4.1.8"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -85,22 +90,23 @@
"dev": true,
"dependencies": {
"@oh-my-opencode/utils": "workspace:*",
- "posthog-node": "^5.51.1"
+ "posthog-node": "^5.52.4"
}
},
"components/comment-checker": {
"name": "@code-yeongyu/codex-comment-checker",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"bin": {
"omo-comment-checker": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
+ "@biomejs/biome": "2.5.14",
"@oh-my-opencode/comment-checker-core": "file:../../../../comment-checker-core",
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -111,12 +117,12 @@
},
"components/git-bash": {
"name": "@sisyphuslabs/codex-git-bash-hook",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"bin": {
"omo-git-bash-hook": "dist/cli.js"
},
"devDependencies": {
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
"typescript": "^7.0.2"
},
"engines": {
@@ -125,16 +131,17 @@
},
"components/lazycodex-executor-verify": {
"name": "@code-yeongyu/codex-lazycodex-executor-verify",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"bin": {
"lazycodex-executor-verify": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -142,7 +149,7 @@
},
"components/lsp": {
"name": "@code-yeongyu/codex-lsp",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"dependencies": {
"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",
@@ -152,10 +159,11 @@
"omo-lsp": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -163,7 +171,7 @@
},
"components/rules": {
"name": "@code-yeongyu/codex-rules",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"dependencies": {
"picomatch": "^4.0.7"
@@ -172,12 +180,13 @@
"omo-rules": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
+ "@biomejs/biome": "2.5.14",
"@oh-my-opencode/rules-engine": "file:../../../../rules-engine",
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
"@types/picomatch": "^4.0.3",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -185,12 +194,13 @@
},
"components/teammode": {
"name": "@sisyphuslabs/codex-teammode",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"devDependencies": {
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"bun-types": "^1.4.2",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -198,17 +208,18 @@
},
"components/telemetry": {
"name": "@code-yeongyu/codex-telemetry",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"bin": {
"omo-telemetry": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
+ "@biomejs/biome": "2.5.14",
"@oh-my-opencode/telemetry-core": "file:../../../../telemetry-core",
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -216,17 +227,18 @@
},
"components/ultrawork": {
"name": "@code-yeongyu/codex-ultrawork",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"bin": {
"omo-ultrawork": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
+ "@biomejs/biome": "2.5.14",
"@oh-my-opencode/prompts-core": "file:../../../../prompts-core",
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -234,16 +246,17 @@
},
"components/ulw-execute-continuation": {
"name": "@code-yeongyu/codex-ulw-execute-continuation",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"bin": {
"omo-ulw-execute-continuation": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
@@ -251,7 +264,7 @@
},
"components/ulw-loop": {
"name": "@code-yeongyu/codex-ulw-loop",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"license": "MIT",
"bin": {
"omo-ulw-loop": "dist/cli.js",
@@ -259,19 +272,80 @@
"ulw-loop": "dist/cli.js"
},
"devDependencies": {
- "@biomejs/biome": "2.5.9",
- "@types/node": "^26.2.0",
+ "@biomejs/biome": "2.5.14",
+ "@types/node": "^26.6.2",
+ "@vitest/coverage-v8": "5.0.1",
"typescript": "^7.0.2",
- "vitest": "^4.1.11"
+ "vitest": "5.0.1"
},
"engines": {
"node": ">=20.0.0"
}
},
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.9",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
+ "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.8"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@bcoe/v8-coverage": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
+ "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@biomejs/biome": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.5.9.tgz",
- "integrity": "sha512-KkgCvdHB4IhtpHpF564plA9jo6fDOwWGQ/3jvreLzgOtRLEDoPqr7QO9qejNA8jKwDsSkAKr77hqBHnyUbIw4g==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.5.14.tgz",
+ "integrity": "sha512-0FabLIjd4M/dm8VFI86RMaLLdgepzbdfiAL2R8cr7V81OYYrP1w7Z73KfAwPK5h9SrEBXTzNG2y+mBwPo9xRnw==",
"dev": true,
"license": "MIT OR Apache-2.0",
"bin": {
@@ -285,20 +359,20 @@
"url": "https://opencollective.com/biome"
},
"optionalDependencies": {
- "@biomejs/cli-darwin-arm64": "2.5.9",
- "@biomejs/cli-darwin-x64": "2.5.9",
- "@biomejs/cli-linux-arm64": "2.5.9",
- "@biomejs/cli-linux-arm64-musl": "2.5.9",
- "@biomejs/cli-linux-x64": "2.5.9",
- "@biomejs/cli-linux-x64-musl": "2.5.9",
- "@biomejs/cli-win32-arm64": "2.5.9",
- "@biomejs/cli-win32-x64": "2.5.9"
+ "@biomejs/cli-darwin-arm64": "2.5.14",
+ "@biomejs/cli-darwin-x64": "2.5.14",
+ "@biomejs/cli-linux-arm64": "2.5.14",
+ "@biomejs/cli-linux-arm64-musl": "2.5.14",
+ "@biomejs/cli-linux-x64": "2.5.14",
+ "@biomejs/cli-linux-x64-musl": "2.5.14",
+ "@biomejs/cli-win32-arm64": "2.5.14",
+ "@biomejs/cli-win32-x64": "2.5.14"
}
},
"node_modules/@biomejs/cli-darwin-arm64": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.5.9.tgz",
- "integrity": "sha512-am22pX2aBqznqq1eMyIj/bZ++riF3Lk6ct7cbv+gQK0csFhr+d8O0RkOi2FF2qSgFgANbqNkIZ0/PxlnW2pLFg==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.5.14.tgz",
+ "integrity": "sha512-UnzaXO65L4tsZimFITFP2M121GyhDcWFrT3pL5ZJ5U4XcS/0L5VHYytVohdCf/gnDUFHgl2I9xnt5bV/J1kxHQ==",
"cpu": [
"arm64"
],
@@ -313,9 +387,9 @@
}
},
"node_modules/@biomejs/cli-darwin-x64": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.5.9.tgz",
- "integrity": "sha512-l44KWDHLDvEnD0N/XcrVs7VXb3A18xL7QS3WB0eL93wbmk529ffIG55vleGCqaunpRUjLrdnjK05Qki1dsjylg==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.5.14.tgz",
+ "integrity": "sha512-kiy8qA16K93J7uvFfWi4LgjqDpnRKyePAna6A0Y4jxyUga35SYpIZ2cNWlhy0lsfgqRenCpfymnJWEZ6mgpRgA==",
"cpu": [
"x64"
],
@@ -330,13 +404,16 @@
}
},
"node_modules/@biomejs/cli-linux-arm64": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.5.9.tgz",
- "integrity": "sha512-ICaK+IYaVZvKbBxX2rwrPT0DdUDMnE9Vm3nQGe+mltQPmUg19pONzkPWGdY4FCsoreDETWDynvdt4ysCbF5gNQ==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.5.14.tgz",
+ "integrity": "sha512-vO/9BaU1n30CiFNLx49gMTMtbCAAqlo/EqFoG0BU3deQInTbJrmXSmTQ9e3FoDZIKQnvSLDVNL4lx1ci7y1T1Q==",
"cpu": [
"arm64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -347,13 +424,16 @@
}
},
"node_modules/@biomejs/cli-linux-arm64-musl": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.5.9.tgz",
- "integrity": "sha512-7ImVPwBLCtkmpR5esd8RHhTqW94f0JLJQum6AneYcy94jRm18TaPPm7slaigGzFhfgt3QiD1Vj52LKmBAnKizA==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.5.14.tgz",
+ "integrity": "sha512-SJ9PrZkBnnH9dHJDnxk34vKs0GB2dbsioaft6/hPhWJ7AHpwYH83Isnhj0FSRpFkGgpVfJ1lds23ApB2czUDLQ==",
"cpu": [
"arm64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -364,13 +444,16 @@
}
},
"node_modules/@biomejs/cli-linux-x64": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.5.9.tgz",
- "integrity": "sha512-z22Q/zFYSvbIJfW1CbfZPu4X8PddS6Qd2ORbc6h+aT6EcwAxUF3m6fA4HjNvA3TU4X0dTJRwNPB165ES3PJXzg==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.5.14.tgz",
+ "integrity": "sha512-VHZRa7CCQBUWKxNwUvHJeuW03WFRgN5NWO//SDGOitc9QIeNyfA42V9zlKm+x82xFSG9Bzi5fi+hbhm9anO8yA==",
"cpu": [
"x64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -381,13 +464,16 @@
}
},
"node_modules/@biomejs/cli-linux-x64-musl": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.5.9.tgz",
- "integrity": "sha512-RXGaD0o1/pTTguYw1aeDJh9ad6Lfrui0fI7mBderTyGr7WuUJkBIttgLkR3XJyoxOkkgfBDspaUT8wXArTqLZw==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.5.14.tgz",
+ "integrity": "sha512-2kI5PrMgW5dcEZYrstLPmUmCwkUwZY39rP4BN93Vxbwcs2O57LDQOktUZZYPvvspN5i0mhGr3TJtF5sU26NUWg==",
"cpu": [
"x64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -398,9 +484,9 @@
}
},
"node_modules/@biomejs/cli-win32-arm64": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.5.9.tgz",
- "integrity": "sha512-nHK+/HHC+D0ogAHUxomgoSTdjImb6fmNNVTKmf0tyu4eDL1DqPKIHc+i+UL8+b0RnAu8224qo8F2tCVnaT0A3w==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.5.14.tgz",
+ "integrity": "sha512-pHgAFffmZtaYoxavEsWEYNvcA7NwOIjLyqw2HXyLbt16xYryX0L4fMV2u0G9ag6LNYPIoqWaWqzUcnc6rLGGXg==",
"cpu": [
"arm64"
],
@@ -415,9 +501,9 @@
}
},
"node_modules/@biomejs/cli-win32-x64": {
- "version": "2.5.9",
- "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.5.9.tgz",
- "integrity": "sha512-Yiq0H56LjXSSw/hd9YkXgSLQfzyDJzbzU2TezozxyNw+uKWAqOtqGVvBfzKRRDiaFF5avGAhHdWKx7LtDOShUw==",
+ "version": "2.5.14",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.5.14.tgz",
+ "integrity": "sha512-oJWmBhoHsnhUKIke+0gXDX0mltJrWHA1UyHsrTlXwX0TL64ilVZAo+TYZm97baecV0esBdpzy3k96q+09JaZUQ==",
"cpu": [
"x64"
],
@@ -481,13 +567,34 @@
"resolved": "../../lsp-daemon",
"link": true
},
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/@jridgewell/sourcemap-codec": {
- "version": "1.5.5",
- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true,
"license": "MIT"
},
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
"node_modules/@oh-my-opencode/comment-checker-core": {
"resolved": "../../comment-checker-core",
"link": true
@@ -513,19 +620,20 @@
"link": true
},
"node_modules/@oxc-project/types": {
- "version": "0.146.0",
- "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.146.0.tgz",
- "integrity": "sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA==",
+ "version": "0.150.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.150.0.tgz",
+ "integrity": "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"funding": {
- "url": "https://github.com/sponsors/Boshen"
+ "url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.5.tgz",
- "integrity": "sha512-DLe/i+l8ynIBY7XEQ191TeZvCoowIGa18R+dIV30GW7DiOtp74i/xX8hs8GUjW5ARV7VZuie3d6AumSmCwbeRA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.9.tgz",
+ "integrity": "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw==",
"cpu": [
"arm"
],
@@ -535,14 +643,15 @@
"os": [
"android"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.5.tgz",
- "integrity": "sha512-zXcwKlQApYAOELHd8PwKDFkagYF9Wy4e0RJ+0qnzl9Pjnpj75TEG8ufv40p2J7kCEfwZAsNiuzRIyNNMWT38ig==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.9.tgz",
+ "integrity": "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg==",
"cpu": [
"arm64"
],
@@ -552,14 +661,15 @@
"os": [
"android"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.5.tgz",
- "integrity": "sha512-dK4QakI42nzWgJT5sm4y4y/O//D4OxM75/cH28RLV+nzIN9AY+YsbuUVrUTjlLjXR6vpyxFbSsbmNuJ6BP9sww==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.9.tgz",
+ "integrity": "sha512-IwhlH3qK5urrY8hZiEgGkHKEFN901p/p2bjxCxJlr4GyNnF7wYpUvK+Y43uaRYuC4hpfjzbR3SJC3arX1jGvmw==",
"cpu": [
"arm64"
],
@@ -569,14 +679,15 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-x64": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.5.tgz",
- "integrity": "sha512-fqSALaUu1Wjd1nK2uW2kJDWdLCc8lx1IcY+MTY26Aurfdx19anlzhqXOgCFbBFQnlFDTn4TC1/7Nz4Bl2mLP3A==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.9.tgz",
+ "integrity": "sha512-XxpJfVzFh+jilRxIXUqcfYAYcunIc/XEzIizsOL1fcJee5Sf7H3mH8WlLmfHfluz5amqR88QQo9izKtmMlavAw==",
"cpu": [
"x64"
],
@@ -586,14 +697,15 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.5.tgz",
- "integrity": "sha512-/vCnNxlkxs9tKxNDcyWUePpJ/PgTzxIaVhoM5SmG8UV+GR/IcPam4VYxi7GIMo7PSDuNqlJqvprqii9NqqVCMw==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.9.tgz",
+ "integrity": "sha512-kSfvhmgeWyfkbT3p/1s5vSgboogoah2zkm9fX2zjg2hHxSV7T4KhMWRUUaRk4OXNqoD3QAUeRqLcs1aZOK4U1g==",
"cpu": [
"x64"
],
@@ -603,14 +715,15 @@
"os": [
"freebsd"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.5.tgz",
- "integrity": "sha512-abk0NLA519LxRCszmbE0jYKuQ9YPocOXTiOXOo6Yr+YAT95VH+PtqYAjOJvGKt3viEd/x4qzabAlwd5bHOOARg==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.9.tgz",
+ "integrity": "sha512-1RVzG17pxqbTfYLC352JlLt6kKLG+6Hr30n8DlIJqsnV5luUDd2Qdx9Ayw1Cabfyb1K9k0jXEZ7evxkRoT+uiw==",
"cpu": [
"arm"
],
@@ -620,116 +733,141 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.5.tgz",
- "integrity": "sha512-Y7eALiJ8lr0M2HH103Js+g7V34wf6snlpZLAsHI90uLhr3PVlNsbFVAXJC9d/V6BnPyKtpSwI+NcB/RLxsQxuA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.9.tgz",
+ "integrity": "sha512-BXqPvZ2drqVD+/Z8UpKwcs4Mp7grM+eGFku4CAEKrEtcbAsUpzREphK1sogCRZGreVPiMkiiBtw0n3TPteuqvw==",
"cpu": [
"arm64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.5.tgz",
- "integrity": "sha512-xMvZgnbZg4YVnR/AX2b3oOPDTFYJvUVaJg5FedA/LuvexAtXibZQej4cnTkw3rjsJ/ggUROB64TdtETiim+FYA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.9.tgz",
+ "integrity": "sha512-11vWvo8YDwLzukt27J3aYDWU+gg2P7J+ZOmiJ0hkF5BXZDW7pVya7r40MXDy6ya0i9KamoENSVKIugvJNgFXIA==",
"cpu": [
"arm64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.5.tgz",
- "integrity": "sha512-GRjeqTUDHTo5GwntsLaAMcBahG3nlpjftXWZLN73HiYQlhwEowvarFgQnRnQZtIp4keXX7quXFbG38uPZBa2EA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.9.tgz",
+ "integrity": "sha512-a1tijMkdwsIARtc0F39ApURROkf3NwqinI6TOiSSWCTR7dT96dffNvMUtDHnq64wKNTIZOIlzKrFvvFUznJiyw==",
"cpu": [
"ppc64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.5.tgz",
- "integrity": "sha512-vLNTR45F2Uwc8AufkNXPmB4VliaXs+FvcheEogIzOXzO4l+LzieXF5A/TWxLy5HtqpsRCHUfd0lPVrrdgXdLHQ==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.9.tgz",
+ "integrity": "sha512-x6SQNdAvv4c3hWqTMaWuawzMX9myaCs/yEmlGsxJzkdClnHW7FbrjQuSiRDhuSYzEYoEMhsaJy9qHG/XNemJPQ==",
"cpu": [
"s390x"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.5.tgz",
- "integrity": "sha512-Mgj59/HTuYeK9Gz2MA+mBWKnHsAgkBSec15ZMb1st3oIfFbX7gCjOae7GydHhzcyQi9Z/7M1QuN9bR3oFqF0jQ==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.9.tgz",
+ "integrity": "sha512-9s0AZ8BFK5/n7B/TBoa2yJE3gI3KURrbXcPBlsAsvjU4VeJKgE90y1YtNxyEUIcHPQkg6/yfF3qihUrcM/Kf0Q==",
"cpu": [
"x64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.5.tgz",
- "integrity": "sha512-mY8AP0/ichsbhAxGnLa3d3+MwV0EfgrPND2bplI3Ym8T6R2pJ0N87bvrKVwNXmdy3jnr6eQBecdqx/HMknBmpA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.9.tgz",
+ "integrity": "sha512-P7VWAmV+WdJluH7ovnRGoiv2i8To7GAZ+kGzfGup635cyL7SyYl3lSUaA3Gp5THf0n/Co5EyEqb2zbqq+nMOHQ==",
"cpu": [
"x64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.5.tgz",
- "integrity": "sha512-8SLssA2oweAxyRgDp789ACfRb/3P+zNRJpzZxSizxF9m8NUDQ4+3xjo8ttjhVGGw6Qxb70oZiEtIjaKikCO7Yw==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.9.tgz",
+ "integrity": "sha512-1qixtsE4BK8h+yS3BfmZ09UhA7O/N4IACva6YBr7EBvCJraByTuRcgOTaiA62Tm0vey3UcKXLOaoGHtYmNGEVg==",
"cpu": [
"arm64"
],
@@ -739,14 +877,15 @@
"os": [
"openharmony"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.5.tgz",
- "integrity": "sha512-vGbruD5zquhoc8D9SViXgN2FBJtNdTyQ4DtG+SWiEGlJiAzoKcZ2xp+xuXCffhubVdt0NJlTZqkeRuERy7g8Cw==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.9.tgz",
+ "integrity": "sha512-ok8IQjcEPs1AKZfuEUznVBrJw+gK4soq+bx8b1X2XoMqVClarc1q5JDmVtWXY1xfr6ZuHTAsPXHTgTrqKTZeww==",
"cpu": [
"arm64"
],
@@ -756,14 +895,15 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.5.tgz",
- "integrity": "sha512-e/SXpgISz+IoqVcSSI0rx/d/he8zqLex+/rCWpnHpmVfmPIUjag9H6P7zotf0gJHwPUhQxZ/mF8tr6acebT9yw==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.9.tgz",
+ "integrity": "sha512-Ip2mXoU0hM0boq3Rf+ekuT653OROSo6aSYcPT1VHE4q52KvyxgFkQgrgb/IEsxOuvQ2fZZbs8khJAyCEPM24/g==",
"cpu": [
"x64"
],
@@ -773,6 +913,7 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
@@ -782,7 +923,8 @@
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "peer": true
},
"node_modules/@sisyphuslabs/codex-git-bash-hook": {
"resolved": "components/git-bash",
@@ -792,13 +934,6 @@
"resolved": "components/teammode",
"link": true
},
- "node_modules/@standard-schema/spec": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
- "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -825,13 +960,13 @@
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "26.2.0",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
- "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
+ "version": "26.6.2",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.2.tgz",
+ "integrity": "sha512-X1P21scMv4zGKLYqjdGjaKa7COa0RKVYYZZN/NfvLQ1JegxFhdhpZG/Lyn8AXx6CDUavKAd11v6BvfpkDByK8g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "undici-types": "~8.3.0"
+ "undici-types": "~8.9.0"
}
},
"node_modules/@types/picomatch": {
@@ -1181,119 +1316,96 @@
"node": ">=16.20.0"
}
},
- "node_modules/@vitest/expect": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
- "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
+ "node_modules/@vitest/coverage-v8": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.0.1.tgz",
+ "integrity": "sha512-FRC8ACiudC3dI6MTplzRSYWHDRnIv2IPfbzs4FdoJNsMal/35sWV8hwIfV8ZcqzSPy+uXHeMVONt9CEqtOU17w==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@standard-schema/spec": "^1.1.0",
- "@types/chai": "^5.2.2",
- "@vitest/spy": "4.1.11",
- "@vitest/utils": "4.1.11",
- "chai": "^6.2.2",
- "tinyrainbow": "^3.1.0"
- },
- "funding": {
- "url": "https://opencollective.com/vitest"
- }
- },
- "node_modules/@vitest/mocker": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
- "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@vitest/spy": "4.1.11",
- "estree-walker": "^3.0.3",
- "magic-string": "^0.30.21"
+ "@bcoe/v8-coverage": "^1.0.2",
+ "@vitest/istanbul-lib-coverage": "^1.0.0",
+ "@vitest/istanbul-lib-report": "^1.0.0",
+ "ast-v8-to-istanbul": "^1.0.5",
+ "magicast": "^0.5.4",
+ "obug": "^2.1.4",
+ "std-env": "^4.2.0",
+ "tinyrainbow": "^3.1.1"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
- "msw": "^2.4.9",
- "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ "@vitest/browser": "5.0.1",
+ "vitest": "5.0.1"
},
"peerDependenciesMeta": {
- "msw": {
- "optional": true
- },
- "vite": {
+ "@vitest/browser": {
"optional": true
}
}
},
- "node_modules/@vitest/pretty-format": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
- "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
+ "node_modules/@vitest/istanbul-lib-coverage": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-1.0.1.tgz",
+ "integrity": "sha512-k3DJZ8LhMBK9NS4SclF1ASD3OgXEWDorbIcPTRDK0/Zae6fRvu+fJRxtFdLfHsa9Y24beCdPnoNZ4LviTNstfA==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "tinyrainbow": "^3.1.0"
- },
- "funding": {
- "url": "https://opencollective.com/vitest"
+ "engines": {
+ "node": ">=22"
}
},
- "node_modules/@vitest/runner": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
- "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
+ "node_modules/@vitest/istanbul-lib-report": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-1.0.1.tgz",
+ "integrity": "sha512-1EOLRfsTMnyAr3+kEAsP4o9dhaDlGPpD7H5iLBBeq//YpNB1VIahkPhB+eRp9N2Dkfw8oySROjE3yf9XDeaIkQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/utils": "4.1.11",
- "pathe": "^2.0.3"
+ "@vitest/istanbul-lib-coverage": "1.0.1"
},
- "funding": {
- "url": "https://opencollective.com/vitest"
+ "engines": {
+ "node": ">=22"
}
},
- "node_modules/@vitest/snapshot": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
- "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
+ "node_modules/@vitest/mocker": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.1.tgz",
+ "integrity": "sha512-6K1DoBNAPGvuOcSsGA4D6x+5zEEff/KmOOP3uetT2TrGpVfI+HRHRnJJfKi5ib/g1vx8IYHQD8s0pbJz8WQI7Q==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "4.1.11",
- "@vitest/utils": "4.1.11",
- "magic-string": "^0.30.21",
- "pathe": "^2.0.3"
+ "@jridgewell/trace-mapping": "0.3.31",
+ "@vitest/spy": "5.0.1",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^1.2.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
}
},
"node_modules/@vitest/spy": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
- "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.1.tgz",
+ "integrity": "sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://opencollective.com/vitest"
}
},
- "node_modules/@vitest/utils": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
- "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@vitest/pretty-format": "4.1.11",
- "convert-source-map": "^2.0.0",
- "tinyrainbow": "^3.1.0"
- },
- "funding": {
- "url": "https://opencollective.com/vitest"
- }
- },
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -1304,6 +1416,18 @@
"node": ">=12"
}
},
+ "node_modules/ast-v8-to-istanbul": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.6.tgz",
+ "integrity": "sha512-fvpl29helSO2w/z7utIbrkNXILdrLwDwAMH2I/zPKlGf5244+gf+B4cyS1sANcrPY2h+hWCGSgC8N61s/+AF9A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "^0.3.31",
+ "estree-walker": "^3.0.3",
+ "js-tokens": "^10.0.0"
+ }
+ },
"node_modules/bun-types": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.4.2.tgz",
@@ -1324,27 +1448,21 @@
"node": ">=18"
}
},
- "node_modules/convert-source-map": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
- "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"engines": {
"node": ">=8"
}
},
"node_modules/es-module-lexer": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz",
- "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==",
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
"dev": true,
"license": "MIT"
},
@@ -1359,9 +1477,9 @@
}
},
"node_modules/expect-type": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
- "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
@@ -1397,16 +1515,25 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/js-tokens": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",
+ "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
"integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
"dev": true,
"license": "MPL-2.0",
+ "peer": true,
"dependencies": {
"detect-libc": "^2.0.3"
},
@@ -1444,6 +1571,7 @@
"os": [
"android"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1465,6 +1593,7 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1486,6 +1615,7 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1507,6 +1637,7 @@
"os": [
"freebsd"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1528,6 +1659,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1544,11 +1676,15 @@
"arm64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1565,11 +1701,15 @@
"arm64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1586,11 +1726,15 @@
"x64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1607,11 +1751,15 @@
"x64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1633,6 +1781,7 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1654,6 +1803,7 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": ">= 12.0.0"
},
@@ -1663,19 +1813,31 @@
}
},
"node_modules/magic-string": {
- "version": "0.30.21",
- "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
- "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.1.tgz",
+ "integrity": "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@jridgewell/sourcemap-codec": "^1.5.5"
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
+ "node_modules/magicast": {
+ "version": "0.5.5",
+ "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz",
+ "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "source-map-js": "^1.2.1"
}
},
"node_modules/nanoid": {
- "version": "3.3.18",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
- "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
+ "version": "3.3.19",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",
"dev": true,
"funding": [
{
@@ -1684,6 +1846,7 @@
}
],
"license": "MIT",
+ "peer": true,
"bin": {
"nanoid": "bin/nanoid.cjs"
},
@@ -1692,29 +1855,26 @@
}
},
"node_modules/obug": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz",
- "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==",
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
"dev": true,
"funding": [
"https://github.com/sponsors/sxzz",
"https://opencollective.com/debug"
],
- "license": "MIT"
- },
- "node_modules/pathe": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
- "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
- "dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
- "license": "ISC"
+ "license": "ISC",
+ "peer": true
},
"node_modules/picomatch": {
"version": "4.0.7",
@@ -1729,9 +1889,9 @@
}
},
"node_modules/postcss": {
- "version": "8.5.26",
- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
- "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
+ "version": "8.5.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
"dev": true,
"funding": [
{
@@ -1748,8 +1908,9 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
- "nanoid": "^3.3.17",
+ "nanoid": "^3.3.18",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -1758,13 +1919,14 @@
}
},
"node_modules/rolldown": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.5.tgz",
- "integrity": "sha512-VD2IE5PUG4Oj8zz2VGykiYd5wbnjdIiSsNQb8Qu5B+noEp+A78mu2iVvpp27g8es14Tk9rofNs5Tku9iQCS4fA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.9.tgz",
+ "integrity": "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
- "@oxc-project/types": "=0.146.0",
+ "@oxc-project/types": "=0.150.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
@@ -1774,21 +1936,21 @@
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
- "@rolldown/binding-android-arm-eabi": "1.2.5",
- "@rolldown/binding-android-arm64": "1.2.5",
- "@rolldown/binding-darwin-arm64": "1.2.5",
- "@rolldown/binding-darwin-x64": "1.2.5",
- "@rolldown/binding-freebsd-x64": "1.2.5",
- "@rolldown/binding-linux-arm-gnueabihf": "1.2.5",
- "@rolldown/binding-linux-arm64-gnu": "1.2.5",
- "@rolldown/binding-linux-arm64-musl": "1.2.5",
- "@rolldown/binding-linux-ppc64-gnu": "1.2.5",
- "@rolldown/binding-linux-s390x-gnu": "1.2.5",
- "@rolldown/binding-linux-x64-gnu": "1.2.5",
- "@rolldown/binding-linux-x64-musl": "1.2.5",
- "@rolldown/binding-openharmony-arm64": "1.2.5",
- "@rolldown/binding-win32-arm64-msvc": "1.2.5",
- "@rolldown/binding-win32-x64-msvc": "1.2.5"
+ "@rolldown/binding-android-arm-eabi": "1.2.9",
+ "@rolldown/binding-android-arm64": "1.2.9",
+ "@rolldown/binding-darwin-arm64": "1.2.9",
+ "@rolldown/binding-darwin-x64": "1.2.9",
+ "@rolldown/binding-freebsd-x64": "1.2.9",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.9",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.9",
+ "@rolldown/binding-linux-arm64-musl": "1.2.9",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.9",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.9",
+ "@rolldown/binding-linux-x64-gnu": "1.2.9",
+ "@rolldown/binding-linux-x64-musl": "1.2.9",
+ "@rolldown/binding-openharmony-arm64": "1.2.9",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.9",
+ "@rolldown/binding-win32-x64-msvc": "1.2.9"
}
},
"node_modules/siginfo": {
@@ -1816,23 +1978,26 @@
"license": "MIT"
},
"node_modules/std-env": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz",
- "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==",
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
"dev": true,
"license": "MIT"
},
"node_modules/tinybench": {
- "version": "2.9.0",
- "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
- "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "version": "6.1.4",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.1.4.tgz",
+ "integrity": "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
},
"node_modules/tinyexec": {
- "version": "1.2.3",
- "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.3.tgz",
- "integrity": "sha512-g62dB+w1/OEFnPvmX0yd/HnetYITOL+1nJW7kitOycOeAvmbWC/nu0fwmmQ/kupNojqExzyC/T++pST/jRJ2mQ==",
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",
+ "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",
"dev": true,
"license": "MIT",
"engines": {
@@ -1902,23 +2067,24 @@
}
},
"node_modules/undici-types": {
- "version": "8.3.0",
- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
- "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/vite": {
- "version": "8.2.2",
- "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz",
- "integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==",
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz",
+ "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"lightningcss": "^1.33.0",
- "picomatch": "^4.0.5",
- "postcss": "^8.5.26",
- "rolldown": "~1.2.4",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.28",
+ "rolldown": "~1.2.6",
"tinyglobby": "^0.2.17"
},
"bin": {
@@ -1935,7 +2101,7 @@
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
- "@vitejs/devtools": "^0.4.0 || ^0.5.0",
+ "@vitejs/devtools": "^0.7.1",
"esbuild": "^0.27.0 || ^0.28.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
@@ -1987,38 +2153,31 @@
}
},
"node_modules/vitest": {
- "version": "4.1.11",
- "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
- "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.1.tgz",
+ "integrity": "sha512-iA95lQbKEkvrtTkdAgnWbXfbipWiiWe/hDl2P5tMi6WFwD76G0NxXAGp/M9EOcYupeGJRr6wppMc7CoA41TQjg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/expect": "4.1.11",
- "@vitest/mocker": "4.1.11",
- "@vitest/pretty-format": "4.1.11",
- "@vitest/runner": "4.1.11",
- "@vitest/snapshot": "4.1.11",
- "@vitest/spy": "4.1.11",
- "@vitest/utils": "4.1.11",
- "es-module-lexer": "^2.0.0",
- "expect-type": "^1.3.0",
- "magic-string": "^0.30.21",
- "obug": "^2.1.1",
- "pathe": "^2.0.3",
- "picomatch": "^4.0.3",
- "std-env": "^4.0.0-rc.1",
- "tinybench": "^2.9.0",
- "tinyexec": "^1.0.2",
- "tinyglobby": "^0.2.15",
- "tinyrainbow": "^3.1.0",
- "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/mocker": "5.0.1",
+ "chai": "^6.2.2",
+ "es-module-lexer": "^2.3.2",
+ "expect-type": "^1.4.0",
+ "magic-string": "^1.2.3",
+ "obug": "^2.1.4",
+ "picomatch": "^4.0.7",
+ "std-env": "^4.2.0",
+ "tinybench": "6.1.4",
+ "tinyexec": "1.3.0",
+ "tinyglobby": "^0.2.17",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
- "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
@@ -2026,16 +2185,16 @@
"peerDependencies": {
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
- "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
- "@vitest/browser-playwright": "4.1.11",
- "@vitest/browser-preview": "4.1.11",
- "@vitest/browser-webdriverio": "4.1.11",
- "@vitest/coverage-istanbul": "4.1.11",
- "@vitest/coverage-v8": "4.1.11",
- "@vitest/ui": "4.1.11",
+ "@types/node": "^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "5.0.1",
+ "@vitest/browser-preview": "5.0.1",
+ "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
+ "@vitest/coverage-istanbul": "5.0.1",
+ "@vitest/coverage-v8": "5.0.1",
+ "@vitest/ui": "5.0.1",
"happy-dom": "*",
"jsdom": "*",
- "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ "vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
diff --git a/plugins/omo/package.json b/plugins/omo/package.json
index 620832e9..75e9ea89 100644
--- a/plugins/omo/package.json
+++ b/plugins/omo/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "5.0.0-beta.80",
+ "version": "5.0.0-beta.81",
"description": "Aggregate Codex plugin root for OMO components.",
"type": "module",
"packageManager": "[email protected]",
@@ -20,6 +20,10 @@
"dependencies": {
"@oh-my-opencode/shared-skills": "file:../../shared-skills"
},
+ "devDependencies": {
+ "@vitest/coverage-v8": "5.0.1",
+ "vitest": "5.0.1"
+ },
"scripts": {
"build": "node scripts/sync-version.mjs && node scripts/sync-hook-status-messages.mjs && node scripts/build-bundled-mcp-runtimes.mjs && node scripts/materialize-shared-upstreams.mjs --strict && node scripts/sync-skills.mjs && node scripts/build-components.mjs",
"sync:version": "node scripts/sync-version.mjs",
diff --git a/plugins/omo/shared/package.json b/plugins/omo/shared/package.json
index 2043a2cf..93ea443c 100644
--- a/plugins/omo/shared/package.json
+++ b/plugins/omo/shared/package.json
@@ -13,7 +13,7 @@
"typecheck": "tsc --noEmit"
},
"devDependencies": {
- "@types/node": "^26.2.0",
+ "@types/node": "^26.6.2",
"bun-types": "1.4.2",
"typescript": "^7.0.2"
},
diff --git a/plugins/omo/skills/frontend/SKILL.md b/plugins/omo/skills/frontend/SKILL.md
index 4bd071bf..fea45d5f 100644
--- a/plugins/omo/skills/frontend/SKILL.md
+++ b/plugins/omo/skills/frontend/SKILL.md
@@ -137,6 +137,7 @@ Domains: `product` `style` `typography` `color` `landing` `chart` `ux` `react` `
- **Concrete reference = contract.** When a screenshot, mockup, or annotated reference exists, match its pixels, copy, component structure, and responsive intent unless the user accepts a deviation.
- **Never weaken UX OR flatten the surface to buy points.** No dropping animations, hiding content, simplifying interactions, or replacing rendered/lit material with flat fills and flat geometric primitives for a Lighthouse score or a deadline. Hit 100 AND keep the surface dimensional — both, or neither.
- **No emojis as icons.** SVG icon sets only (Lucide, Heroicons, Radix, Phosphor).
+- **No coloured accent borders on rounded surfaces.** A `border-l-2 border-primary` stripe on a selected row, a primary-tinted outline on a focused card — any `border-{side}-{primary|warning|destructive|success}` or accent-width rule used to mark selected/focused/active is the most recognizable AI-slop tell in shipped UI. Encode state the way `DESIGN.md` systems do: one ink at many alphas (hover/selected/active wash ramps), a glyph (check) for selection, tonal layering for focus. Keyboard `focus-visible` rings are the only coloured edge allowed. Applies to code you write AND to pre-existing instances on any surface you touch — sweep them out.
- **GPU-composited animation only** — `transform`, `opacity`, `filter`; never animate layout properties.
- **Slop animation is forbidden — motion serves meaning.** Every animation or hover must map to a real interaction, state change, or affordance. A hover that changes nothing, motion on a non-interactive element, or a decorative micro-animation with no informational purpose is slop — do not add it.
- **Done is the `/visual-qa` dual-oracle gate, not your own glance.** A frontend design task is verified through `/visual-qa` (real browser at 375 / 768 / 1280px, every page, with interaction states and motion driven and inspected) until the dual-oracle completion gate passes on fresh evidence.
diff --git a/plugins/omo/skills/frontend/references/design/README.md b/plugins/omo/skills/frontend/references/design/README.md
index ad37a517..f8770f14 100644
--- a/plugins/omo/skills/frontend/references/design/README.md
+++ b/plugins/omo/skills/frontend/references/design/README.md
@@ -202,7 +202,7 @@ Triggers: an animated, shader, particle, or grid background; a hero that must fe
## Anti-patterns — do not do these
- **Don't load nothing and just freestyle.** That produces the exact "generic AI SaaS slop" — purple-blue gradient backgrounds, rounded-2xl-on-everything, three feature cards in a grid, generic Inter font, lorem ipsum. The skills exist precisely to prevent this.
-- **Don't load five files "to be safe".** That blows context and creates contradictory rules. Pick deliberately.
+- **Don't mark state with a coloured accent border.** `border-l-2 border-primary` on the selected row, a primary outline on the focused card — on a rounded surface that is the generic AI tell. State is ink-alpha washes, a glyph for selection, tonal layering for focus; `focus-visible` rings are the only coloured edge. Includes pre-existing instances on surfaces you touch.
- **Don't ignore the user's named brand.** If they say "Linear-style" and you build something that doesn't match Linear's actual aesthetic (purple, ultra-tight spacing, mono accents, etc.), you have failed the routing.
- **Don't apply a Layer B brand verbatim if the project is not that brand.** The DESIGN.md captures *inspiration* — extract the tokens (palette, type scale, component patterns) and apply them to the project's own content. Do not copy logos or trademarked imagery.
- **Don't use imagegen skills to write code.** They are explicitly image-only. The agent has been observed trying to "describe" the image as React code — that is the wrong skill, switch to `image-to-code-skill.md` instead.
@@ -221,7 +221,7 @@ Once references are loaded, before writing any UI code:
7. **Match the project's existing patterns FIRST.** If the codebase already uses CSS Modules, don't introduce Tailwind. If it uses styled-components, don't introduce CSS-in-JS variants. The references guide *style*, not *infrastructure*.
8. **All tokens trace back to `DESIGN.md`.** No orphan hex codes, no magic px values. If you need a new token, update `DESIGN.md` first.
9. **New reusable patterns (used 2+ times) get documented back into `DESIGN.md` Section 5.**
-10. **No generic-default drift (expressive briefs).** The shipped CSS must use the `DESIGN.md` material, not the model's priors. Load the declared fonts (do not silently fall back to Inter or system fonts), build elevated surfaces from the declared multi-layer recipe (not a lone `backdrop-filter: blur`), and color from the ramp stops (not one tint at varied opacity). Grep your styles before QA: finding `Inter`, a single blur on "glass", or one brand hex reused everywhere means you regressed to priors — fix it before declaring done.
+10. **No generic-default drift (expressive briefs).** The shipped CSS must use the `DESIGN.md` material, not the model's priors. Load the declared fonts (do not silently fall back to Inter or system fonts), build elevated surfaces from the declared multi-layer recipe (not a lone `backdrop-filter: blur`), and color from the ramp stops (not one tint at varied opacity). Grep your styles before QA: finding `Inter`, a single blur on "glass", one brand hex reused everywhere, or a coloured accent border marking selected/focused state (`border-l-2 border-primary` et al) means you regressed to priors — fix it before declaring done.
## Quick lookup table — most common requests
@@ -252,6 +252,7 @@ This skill adds only the design-taste judgments `/visual-qa` cannot make for you
1. **Two kinds of failure count equally — fix both, then re-check.** Defects: clipping, wrong font, missing state, jank. Flatness: a surface that reads generic next to the loaded reference. When the render is bug-free but flat, you are NOT done — RAISE the design: deepen the material layering, give the color a real perceptual ramp (multiple stops / OKLCH, not one tint at varied opacity), render the hero focal object as real dimensional material (a generated bitmap, or real light/shadow/gradient/depth — never flat geometric primitives), and add the one signature moment. Patching only bugs while the surface stays at the floor is the single most common way this skill ships clean-but-generic work.
2. **Motion serves meaning; slop animation is forbidden.** Every interactive element must communicate its affordance and state changes — but a hover that changes nothing, motion on a non-interactive element, or a decorative micro-animation with no informational purpose is slop. Do not add it, and treat any you find as a defect. The hero may carry one signature moment; the rest of the surface earns motion only where it signals interaction or state.
+3. **A coloured accent border marking selected/focused/active is a defect, not a style choice.** Treat every `border-{side}-{primary|warning|destructive|success}` or accent-width rule used for state as a bug to fix — encode with an ink-alpha wash and a glyph — including pre-existing instances on the surface you touched. `focus-visible` rings are exempt.
Report "done" only when `/visual-qa` has passed on fresh evidence AND neither a visual bug nor a floor-level or slop-laden surface remains.
diff --git a/plugins/omo/skills/frontend/references/design/design-system-architecture.md b/plugins/omo/skills/frontend/references/design/design-system-architecture.md
index 4f754b01..a52abea0 100644
--- a/plugins/omo/skills/frontend/references/design/design-system-architecture.md
+++ b/plugins/omo/skills/frontend/references/design/design-system-architecture.md
@@ -151,6 +151,7 @@ code; do not invent future components just to fill the section.
### Rules
- Only animate `transform` and `opacity`. Never animate layout properties.
- Every interactive element has hover + active + focus states.
+- Selected/focused/active state is encoded with ink-alpha washes and a glyph (check) — never a coloured accent border or outline. `focus-visible` rings are the only coloured edge.
- Scroll-triggered animations use `IntersectionObserver`, not scroll listeners.
- Reduced motion: respect `prefers-reduced-motion` — disable non-essential animation.
diff --git a/plugins/omo/skills/frontend/references/perfection/README.md b/plugins/omo/skills/frontend/references/perfection/README.md
index 31cf9dcf..fc7ebfc6 100644
--- a/plugins/omo/skills/frontend/references/perfection/README.md
+++ b/plugins/omo/skills/frontend/references/perfection/README.md
@@ -67,6 +67,7 @@ During the audit loop, after Lighthouse scores pass, run a Design System Complia
- **Spacing**: every margin/padding/gap value must be a multiple of the base unit (4px) and ideally use a declared token.
- **Components**: any component used 2+ times must be documented in `DESIGN.md` Section 5. If it isn't, add it.
- **Depth**: if `DESIGN.md` says "borders-only", there must be zero `box-shadow` declarations. If "tonal-shift", zero borders for surface separation.
+- **State borders**: grep for `border(-[trbl])?-(primary|warning|destructive|success)` and accent-width rules (`border-l-2`, `border-l-4`…) used to mark selected/focused/active. Each hit is a violation — state belongs to ink-alpha washes and glyphs. Keyboard `focus-visible` rings are exempt.
A page that scores Lighthouse 100 but uses 14 undeclared hex codes and 8 magic spacing values is **NOT DONE**. The design system is the architecture — Lighthouse measures the performance of that architecture.
diff --git a/plugins/omo/skills/ultimate-browsing/engine/templates/package.json b/plugins/omo/skills/ultimate-browsing/engine/templates/package.json
index 01ab32b1..8104f8e3 100644
--- a/plugins/omo/skills/ultimate-browsing/engine/templates/package.json
+++ b/plugins/omo/skills/ultimate-browsing/engine/templates/package.json
@@ -4,7 +4,7 @@
"private": true,
"description": "Script-only dependencies for local Chrome templates driven from js eval; Chrome must already be installed.",
"dependencies": {
- "playwright-core": "^1.62.1",
+ "playwright-core": "^1.63.0",
"playwright-extra": "^4.3.6",
"puppeteer-extra-plugin-stealth": "^2.11.2"
}