@awell-health/navi-core
Version:
Core utilities and GraphQL client for Navi care flow integration
1,409 lines (1,397 loc) • 129 kB
JavaScript
'use strict';
var jose = require('jose');
/**
* Type guards to safely convert ActivityData to specific types
*/
function isFormActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "FormActivityInput" &&
activity.inputs.form !== null &&
activity.inputs.form !== undefined);
}
function isMessageActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "MessageActivityInput");
}
function isChecklistActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "ChecklistActivityInput");
}
function isDynamicFormActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "DynamicFormActivityInput");
}
function isExtensionActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "ExtensionActivityInput");
}
function isCalculationActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "CalculationActivityInput");
}
function isClinicalNoteActivity(activity) {
return (activity.inputs !== null &&
activity.inputs !== undefined &&
activity.inputs.__typename === "ClinicalNoteActivityInput");
}
/**
* Safe assertion functions with helpful errors
*/
function assertFormActivity(activity) {
if (!isFormActivity(activity)) {
throw new Error(`Expected form activity but got activity type: ${activity.inputs?.__typename || "unknown"}. Make sure this activity has form inputs.`);
}
return activity;
}
function assertMessageActivity(activity) {
if (!isMessageActivity(activity)) {
throw new Error(`Expected message activity but got activity type: ${activity.inputs?.__typename || "unknown"}. Make sure this activity has message inputs.`);
}
return activity;
}
function assertChecklistActivity(activity) {
if (!isChecklistActivity(activity)) {
throw new Error(`Expected checklist activity but got activity type: ${activity.inputs?.__typename || "unknown"}. Make sure this activity has checklist inputs.`);
}
return activity;
}
/**
* Base Navi Error Class
*/
class NaviError extends Error {
constructor(message, code, details) {
super(message);
this.code = code;
this.details = details;
this.name = "NaviError";
}
}
/**
* Authentication Error Types for categorized error handling
*/
exports.AuthErrorType = void 0;
(function (AuthErrorType) {
// Initialization errors
AuthErrorType["NOT_INITIALIZED"] = "NOT_INITIALIZED";
AuthErrorType["INITIALIZATION_FAILED"] = "INITIALIZATION_FAILED";
// Token creation errors
AuthErrorType["INVALID_SESSION_DATA"] = "INVALID_SESSION_DATA";
AuthErrorType["SESSION_TOKEN_CREATION_FAILED"] = "SESSION_TOKEN_CREATION_FAILED";
AuthErrorType["JWT_CREATION_FAILED"] = "JWT_CREATION_FAILED";
// Token verification errors
AuthErrorType["INVALID_TOKEN_FORMAT"] = "INVALID_TOKEN_FORMAT";
AuthErrorType["TOKEN_SIGNATURE_INVALID"] = "TOKEN_SIGNATURE_INVALID";
AuthErrorType["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
// Payload validation errors
AuthErrorType["PAYLOAD_VALIDATION_FAILED"] = "PAYLOAD_VALIDATION_FAILED";
AuthErrorType["MISSING_REQUIRED_CLAIMS"] = "MISSING_REQUIRED_CLAIMS";
AuthErrorType["INVALID_CLAIMS_FORMAT"] = "INVALID_CLAIMS_FORMAT";
// Session conversion errors
AuthErrorType["SESSION_CONVERSION_FAILED"] = "SESSION_CONVERSION_FAILED";
AuthErrorType["INVALID_SESSION_FORMAT"] = "INVALID_SESSION_FORMAT";
// Generic auth failures
AuthErrorType["UNKNOWN_AUTH_ERROR"] = "UNKNOWN_AUTH_ERROR";
})(exports.AuthErrorType || (exports.AuthErrorType = {}));
/**
* Enhanced Authentication Error Class with categorized error types
*
* Provides detailed error categorization for better debugging and error handling.
* Includes validation errors from Zod parsing failures.
*
* @example Error Handling
* ```typescript
* try {
* const payload = await authService.verifyToken(token);
* } catch (error) {
* if (error instanceof NaviAuthError) {
* switch (error.errorType) {
* case AuthErrorType.TOKEN_EXPIRED:
* // Handle expired token - redirect to login
* break;
* case AuthErrorType.PAYLOAD_VALIDATION_FAILED:
* // Handle malformed payload - log security event
* console.log(error.validationErrors);
* break;
* case AuthErrorType.NOT_INITIALIZED:
* // Handle service not initialized
* break;
* }
* }
* }
* ```
*/
class NaviAuthError extends NaviError {
constructor(message, errorType = exports.AuthErrorType.UNKNOWN_AUTH_ERROR, details) {
super(message, `AUTH_${errorType}`, details);
this.errorType = errorType;
this.name = "NaviAuthError";
// Extract validation errors if present
if (details?.validationErrors) {
this.validationErrors = details.validationErrors;
}
}
/**
* Create an authentication error for initialization failures
*/
static notInitialized(message = "Auth service not initialized") {
return new NaviAuthError(message, exports.AuthErrorType.NOT_INITIALIZED);
}
/**
* Create an authentication error for initialization failures
*/
static initializationFailed(error) {
return new NaviAuthError("Failed to initialize auth service", exports.AuthErrorType.INITIALIZATION_FAILED, { error });
}
/**
* Create an authentication error for invalid session data
*/
static invalidSessionData(validationErrors) {
return new NaviAuthError("Invalid session token data", exports.AuthErrorType.INVALID_SESSION_DATA, { validationErrors });
}
/**
* Create an authentication error for session token creation failures
*/
static sessionTokenCreationFailed(error) {
return new NaviAuthError("Failed to create session token", exports.AuthErrorType.SESSION_TOKEN_CREATION_FAILED, { error });
}
/**
* Create an authentication error for JWT creation failures
*/
static jwtCreationFailed(error) {
return new NaviAuthError("Failed to create JWT from session", exports.AuthErrorType.JWT_CREATION_FAILED, { error });
}
/**
* Create an authentication error for invalid tokens
*/
static invalidToken(message = "Invalid or expired token", error) {
// Determine specific error type based on the underlying error
let errorType = exports.AuthErrorType.INVALID_TOKEN_FORMAT;
if (error?.code === "ERR_JWT_EXPIRED") {
errorType = exports.AuthErrorType.TOKEN_EXPIRED;
}
else if (error?.code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") {
errorType = exports.AuthErrorType.TOKEN_SIGNATURE_INVALID;
}
return new NaviAuthError(message, errorType, { error });
}
/**
* Create an authentication error for payload validation failures
*/
static payloadValidationFailed(validationErrors) {
return new NaviAuthError("Token payload validation failed", exports.AuthErrorType.PAYLOAD_VALIDATION_FAILED, { validationErrors });
}
/**
* Create an authentication error for session conversion failures
*/
static sessionConversionFailed(validationErrors) {
return new NaviAuthError("Invalid session data for JWT creation", exports.AuthErrorType.SESSION_CONVERSION_FAILED, { validationErrors });
}
/**
* Create an authentication error for session token validation failures
*/
static sessionTokenValidationFailed(validationErrors) {
return new NaviAuthError("Session token validation failed", exports.AuthErrorType.INVALID_SESSION_FORMAT, { validationErrors });
}
}
/**
* Network Error Class
*/
class NaviNetworkError extends NaviError {
constructor(message, details) {
super(message, "NETWORK_ERROR", details);
this.name = "NaviNetworkError";
}
}
/** A special constant with type `never` */
function $constructor(name, initializer, params) {
function init(inst, def) {
var _a;
Object.defineProperty(inst, "_zod", {
value: inst._zod ?? {},
enumerable: false,
});
(_a = inst._zod).traits ?? (_a.traits = new Set());
inst._zod.traits.add(name);
initializer(inst, def);
// support prototype modifications
for (const k in _.prototype) {
if (!(k in inst))
Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
}
inst._zod.constr = _;
inst._zod.def = def;
}
// doesn't work if Parent has a constructor with arguments
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 _;
}
class $ZodAsyncError extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
}
const globalConfig = {};
function config(newConfig) {
return globalConfig;
}
// functions
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 jsonStringifyReplacer(_, value) {
if (typeof value === "bigint")
return value.toString();
return value;
}
function cached(getter) {
return {
get value() {
{
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
}
},
};
}
function nullish(input) {
return input === null || input === undefined;
}
function cleanRegex(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return (valInt % stepInt) / 10 ** decCount;
}
function defineLazy(object, key, getter) {
Object.defineProperty(object, key, {
get() {
{
const value = getter();
object[key] = value;
return value;
}
},
set(v) {
Object.defineProperty(object, key, {
value: v,
// configurable: true,
});
// object[key] = v;
},
configurable: true,
});
}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
const descriptors = Object.getOwnPropertyDescriptors(def);
Object.assign(mergedDescriptors, descriptors);
}
return Object.defineProperties({}, mergedDescriptors);
}
function esc(str) {
return JSON.stringify(str);
}
const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
const allowsEval = cached(() => {
// @ts-ignore
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
return false;
}
try {
const F = Function;
new F("");
return true;
}
catch (_) {
return false;
}
});
function isPlainObject(o) {
if (isObject(o) === false)
return false;
// modified constructor
const ctor = o.constructor;
if (ctor === undefined)
return true;
// modified prototype
const prot = ctor.prototype;
if (isObject(prot) === false)
return false;
// ctor doesn't have static `isPrototypeOf`
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
return false;
}
return true;
}
const propertyKeyTypes = new Set(["string", "number", "symbol"]);
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// zod-specific utils
function clone(inst, def, params) {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || params?.parent)
cl._zod.parent = inst;
return cl;
}
function normalizeParams(_params) {
const params = _params;
if (!params)
return {};
if (typeof params === "string")
return { error: () => params };
if (params?.message !== undefined) {
if (params?.error !== undefined)
throw new Error("Cannot specify both `message` and `error` params");
params.error = params.message;
}
delete params.message;
if (typeof params.error === "string")
return { ...params, error: () => params.error };
return params;
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
});
}
const NUMBER_FORMAT_RANGES = {
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-34028234663852886e22, 3.4028234663852886e38],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
};
function pick(schema, mask) {
const currDef = schema._zod.def;
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); // self-caching
return newShape;
},
checks: [],
});
return clone(schema, def);
}
function omit(schema, mask) {
const currDef = schema._zod.def;
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); // self-caching
return newShape;
},
checks: [],
});
return clone(schema, def);
}
function extend(schema, shape) {
if (!isPlainObject(shape)) {
throw new Error("Invalid input to extend: expected a plain object");
}
const def = mergeDefs(schema._zod.def, {
get shape() {
const _shape = { ...schema._zod.def.shape, ...shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
checks: [],
});
return clone(schema, def);
}
function merge(a, b) {
const def = mergeDefs(a._zod.def, {
get shape() {
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
get catchall() {
return b._zod.def.catchall;
},
checks: [], // delete existing checks
});
return clone(a, def);
}
function partial(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 oldShape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key],
})
: oldShape[key];
}
}
else {
for (const key in oldShape) {
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key],
})
: oldShape[key];
}
}
assignProp(this, "shape", shape); // self-caching
return shape;
},
checks: [],
});
return clone(schema, def);
}
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;
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key],
});
}
}
else {
for (const key in oldShape) {
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key],
});
}
}
assignProp(this, "shape", shape); // self-caching
return shape;
},
checks: [],
});
return clone(schema, def);
}
function aborted(x, startIndex = 0) {
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue !== true) {
return true;
}
}
return false;
}
function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
(_a = iss).path ?? (_a.path = []);
iss.path.unshift(path);
return iss;
});
}
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config) {
const full = { ...iss, path: iss.path ?? [] };
// for backwards compatibility
if (!iss.message) {
const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
unwrapMessage(ctx?.error?.(iss)) ??
unwrapMessage(config.customError?.(iss)) ??
unwrapMessage(config.localeError?.(iss)) ??
"Invalid input";
full.message = message;
}
// delete (full as any).def;
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) {
delete full.input;
}
return full;
}
function getLengthableOrigin(input) {
if (Array.isArray(input))
return "array";
if (typeof input === "string")
return "string";
return "unknown";
}
function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") {
return {
message: iss,
code: "custom",
input,
inst,
};
}
return { ...iss };
}
const initializer$1 = (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,
});
};
const $ZodError = $constructor("$ZodError", initializer$1);
const $ZodRealError = $constructor("$ZodError", initializer$1, { 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));
}
}
return { formErrors, fieldErrors };
}
function formatError(error, _mapper) {
const mapper = _mapper ||
function (issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
issue.errors.map((issues) => processError({ issues }));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues });
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues });
}
else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.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++;
}
}
}
};
processError(error);
return fieldErrors;
}
const _parse = (_Err) => (schema, value, _ctx, _params) => {
const ctx = _ctx ? Object.assign(_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;
}
return result.value;
};
const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx = _ctx ? Object.assign(_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;
};
const _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 };
};
const safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError);
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_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 };
};
const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
const cuid = /^[cC][^\s-]{8,}$/;
const cuid2 = /^[0-9a-z]+$/;
const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
const xid = /^[0-9a-vA-V]{20}$/;
const ksuid = /^[A-Za-z0-9]{27}$/;
const nanoid = /^[a-zA-Z0-9_-]{21}$/;
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
/** Returns a regex for validating an RFC 9562/4122 UUID.
*
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
const 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)$/;
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})$`);
};
/** Practical email validation */
const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
return new RegExp(_emoji$1, "u");
}
const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
const base64url = /^[A-Za-z0-9_-]*$/;
// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
// export const hostname: RegExp =
// /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
const date$1 = /*@__PURE__*/ new RegExp(`^${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+)?)?`;
return regex;
}
function time$1(args) {
return new RegExp(`^${timeSource(args)}$`);
}
// Adapted from https://stackoverflow.com/a/3143231
function datetime$1(args) {
const time = timeSource({ precision: args.precision });
const opts = ["Z"];
if (args.local)
opts.push("");
if (args.offset)
opts.push(`([+-]\\d{2}:\\d{2})`);
const timeRegex = `${time}(?:${opts.join("|")})`;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
const string$1 = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
const integer = /^\d+$/;
const number$1 = /^-?\d+(?:\.\d+)?/i;
// regex for string with no uppercase letters
const lowercase = /^[^A-Z]*$/;
// regex for string with no lowercase letters
const uppercase = /^[^a-z]*$/;
// import { $ZodType } from "./schemas.js";
const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date",
};
const $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,
code: "too_big",
maximum: def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
const $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,
code: "too_small",
minimum: def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
const $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;
if (isMultiple)
return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def); // no format checks
def.format = def.format || "float64";
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) {
if (!Number.isInteger(input)) {
// invalid_format issue
// payload.issues.push({
// expected: def.format,
// format: def.format,
// code: "invalid_format",
// input,
// inst,
// });
// invalid_type issue
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
input,
inst,
});
return;
// not_multiple_of issue
// payload.issues.push({
// code: "not_multiple_of",
// origin: "number",
// input,
// inst,
// divisor: 1,
// });
}
if (!Number.isSafeInteger(input)) {
if (input > 0) {
// too_big
payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
continue: !def.abort,
});
}
else {
// too_small
payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
continue: !def.abort,
});
}
return;
}
}
if (input < minimum) {
payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inst,
});
}
};
});
const $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;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length <= def.maximum)
return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
const $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;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length >= def.minimum)
return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
const $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;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length === def.length)
return;
const origin = getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
const $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;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...(def.pattern ? { pattern: def.pattern.toString() } : {}),
inst,
continue: !def.abort,
});
});
else
(_b = inst._zod).check ?? (_b.check = () => { });
});
const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort,
});
};
});
const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = lowercase);
$ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = uppercase);
$ZodCheckStringFormat.init(inst, def);
});
const $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);
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;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
$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;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
$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;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
class Doc {
constructor(args = []) {
this.content = [];
this.indent = 0;
if (this)
this.args = args;
}
indented(fn) {
this.indent += 1;
fn(this);
this.indent -= 1;
}
write(arg) {
if (typeof arg === "function") {
arg(this, { execution: "sync" });
arg(this, { execution: "async" });
return;
}
const content = arg;
const lines = content.split("\n").filter((x) => x);
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
for (const line of dedented) {
this.content.push(line);
}
}
compile() {
const F = Function;
const args = this?.args;
const content = this?.content ?? [``];
const lines = [...content.map((x) => ` ${x}`)];
// console.log(lines.join("\n"));
return new F(...args, lines.join("\n"));
}
}
const version = {
major: 4,
minor: 0,
patch: 10,
};
const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
var _a;
inst ?? (inst = {});
inst._zod.def = def; // set _def property
inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
inst._zod.version = version;
const checks = [...(inst._zod.def.checks ?? [])];
// if inst is itself a checks.$ZodCheck, run it as a check
if (inst._zod.traits.has("$ZodCheck")) {
checks.unshift(inst);
}
//
for (const ch of checks) {
for (const fn of ch._zod.onattach) {
fn(inst);
}
}
if (checks.length === 0) {
// deferred initializer
// inst._zod.parse is not yet defined
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred?.push(() => {
inst._zod.run = inst._zod.parse;
});
}
else {
const runChecks = (payload, checks, ctx) => {
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
if (ch._zod.def.when) {
const shouldRun = ch._zod.def.when(payload);
if (!shouldRun)
continue;
}
else if (isAborted) {
continue;
}
const currLen = payload.issues.length;
const _ = ch._zod.check(payload);
if (_ instanceof Promise && ctx?.async === false) {
throw new $ZodAsyncError();
}
if (asyncResult || _ instanceof Promise) {
asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
await _;
const nextLen = payload.issues.length;
if (nextLen === currLen)
return;
if (!isAborted)
isAborted = aborted(payload, currLen);
});
}
else {
const nextLen = payload.issues.length;
if (nextLen === currLen)
continue;
if (!isAborted)
isAborted = aborted(payload, currLen);
}
}
if (asyncResult) {
return asyncResult.then(() => {
return payload;
});
}
return payload;
};
inst._zod.run = (payload, ctx) => {
const result = inst._zod.parse(payload, ctx);
if (result instanceof Promise) {
if (ctx.async === false)
throw new $ZodAsyncError();
return result.then((result) => runChecks(result, checks, ctx));
}
return runChecks(result, checks, ctx);
};
}
inst["~standard"] = {
validate: (value) => {
try {
const r = safeParse$1(inst, value);
return r.success ? { value: r.data } : { issues: r.error?.issues };
}
catch (_) {
return safeParseAsync$1(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
}
},
vendor: "zod",
version: 1,
};
});
const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
inst._zod.parse = (payload, _) => {
if (def.coerce)
try {
payload.value = String(payload.value);
}
catch (_) { }
if (typeof payload.value === "string")
return payload;
payload.issues.push({
expected: "string",
code: "invalid_type",
input: payload.value,
inst,
});
return payload;
};
});
const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
// check initialization must come first
$ZodCheckStringFormat.init(inst, def);
$ZodString.init(inst, def);
});
const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
def.pattern ?? (def.pattern = guid);
$ZodStringFormat.init(inst, def);
});
const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
if (def.version) {
const versionMap = {
v1: 1,
v2: 2,
v3: 3,
v4: 4,
v5: 5,
v6: 6,
v7: 7,
v8: 8,
};
const v = versionMa